-1

In my woocommerce cart, the shipping cost is still correctly calculated by the code below. But the shipping label is not being updated now. I can't found the cause; could be the recently woocommerce 3.7 update? Thanks for help!

/**
 * Add different price for shipping based on products quantity
 */
function mx_shop_shipping_price( $rates, $package ) {
    //Shipping Mode 1
    if ( WC()->cart->cart_contents_count < 4 ) {
        return array_filter($rates, function (WC_Shipping_Rate $rate) {
            return $rate->get_label() === 'Shipping Mode 1'; // Shipping Mode 1
        });
    }
    //Shipping Mode 2
    if ( WC()->cart->cart_contents_count < 13 ) {
        return array_filter($rates, function (WC_Shipping_Rate $rate) {
            return $rate->get_label() === 'Shipping Mode 2';
        });
    }
    //Shipping Mode 3
    return array_filter($rates, function (WC_Shipping_Rate $rate) {
        return $rate->get_label() === 'Shipping Mode 3';
    });     
}
add_filter( 'woocommerce_package_rates', 'mx_shop_shipping_price', 10, 2 );

/** End

Cart detail with Shipping label not updated. Note Order Total is correctly updated

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399

1 Answers1

0

You're using comparison operator '===' instead of assignment operator. Here is your updated code that you can try:

function mx_shop_shipping_price( $rates, $package ) {
    //Shipping Mode 1
    if ( WC()->cart->cart_contents_count < 4 ) {
        return array_filter($rates, function (WC_Shipping_Rate $rate) {
            return  $rates[$rate_key]->label = __( 'Shipping Mode 1', 'woocommerce' ); // Shipping Mode 1
        });
    }
    //Shipping Mode 2
    if ( WC()->cart->cart_contents_count < 13 ) {
        return array_filter($rates, function (WC_Shipping_Rate $rate) {
            return $rates[$rate_key]->label = __( 'Shipping Mode 2', 'woocommerce' );
        });
    }
    //Shipping Mode 3
    return array_filter($rates, function (WC_Shipping_Rate $rate) {
        return $rates[$rate_key]->label = __( 'Shipping Mode 3', 'woocommerce' );;
    });     
}
add_filter( 'woocommerce_package_rates', 'mx_shop_shipping_price', 10, 2 );

You should need to refresh the shipping caches:

1) First this code is already saved on your function.php file.

2) In Shipping settings, enter in a Shipping Zone and disable a Shipping Method and "save".

Then re-enable that Shipping Method and "save". You are done.

You can find answer already given for such requirement here

Vantiya
  • 612
  • 1
  • 4
  • 11
  • My code SET the shipping rate! The comparision operator is used to return the rate matching the label "Shipping Mode n". Before the label was automatically updated. – Matricolon Oct 02 '19 at 15:18