Viewing 1 replies (of 1 total)
  • Thread Starter Vikas Khunteta

    (@vikas_khunteta)

    I have been digging for solution and I forward one step ahead but haven’t got solution yet.

    Regarding the problem I found why the “\r\n” are coming?

    I used woocommerce_before_calculate_totals hook to update product price dynamically. As I have been using addons so if user add some addon the price should be included into product price that’s why I wrote the below code.

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_field_price', 10, 1);
    
    function add_custom_field_price( $cart_obj )
    {
        //  This is necessary for WC 3.0+
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        foreach ( $cart_obj->get_cart() as $key => $value ) {
            $product = wc_get_product( $value['product_id'] );
            $variable_product = wc_get_product( $value['variation_id'] );
            if ( array_key_exists( 'addons', $value ) ) {
                $addons = $value['addons'];
                foreach ( $addons as $group_name => $addon ) {
    
                    $price = 0;
                    foreach ( $addon as $addon_name ) {
                        $actual_addon_name = str_ireplace( array( 'no ', 'less ', 'more ' ), '', $addon_name );
                        $addon_price = floatval( get_price_by_addon_name( $value['product_id'], $group_name, $actual_addon_name ) );
                        $addon_name_words = explode( " ", $addon_name );
                        if ( $addon_name_words[0] !== "No" ) {
                            $price += $addon_price;
                        }
                    }
    
                    if ( $variable_product ) {
                        $product_price = $variable_product->price + $price;
                    } else {
                        $product_price = $product->price + $price;
                    }
                    $value['data']->set_price( $product_price );
                }
            }
        }
    }

    Let me explain the $addons data, it have group name as key and all selected addon as value(array), so basically its a multidimensional array. The addon name may have options like “No”, “Less” or “More” which added before its name.

    The problem arise when third foreach loop run, the $addon array loop. Now I don’t understand why “\r\n” added when this loop run.

Viewing 1 replies (of 1 total)

The topic ‘WooCommerce Product Metadata Output Issue’ is closed to new replies.