phpwordpresswoocommercecart

Disable shipping method when a cart item has a specific shipping class?


I try to disable a shipping method if a specific shipping class is in the cart. I'm using the newest woocommerce version.

Below is my Code for my task. It's placed at the end of my functions.php file of my Theme.

Sadly its not working.

add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_free_shipping_for_shipping_class', 10, 2 );
function businessbloomer_hide_free_shipping_for_shipping_class( $rates, $package ) {
    $shipping_class_target = 513;           // ID OF MY SHIPPING_CLASS
    $in_cart = false;
    foreach( WC()->cart->cart_contents as $key => $values ) {
        if( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
            $in_cart = true;
            break;
        } 
    }
    if( $in_cart ) {
        unset( $rates['flat_rate:2'] );     //VALUE:ID OF MY SHIPPING METHOD
    }
    return $rates;
}

Solution

  • I have tested simplifying a little your code (with the ids of my WC settings) and it works:

    add_filter( 'woocommerce_package_rates', 'custom_hide_shipping_methods', 10, 2 );
    function custom_hide_shipping_methods( $rates, $package ) {
        foreach( WC()->cart->get_cart() as $cart_item  ) {
            $product = $cart_item[ 'data' ]; // The WC_Product object
            $shipping_class_id = $product->get_shipping_class_id();
    
            if( isset($rates['flat_rate:2']) && $shipping_class_id == 513 ) { // <== ID OF MY SHIPPING_CLASS
                unset( $rates['flat_rate:2'] ); // Removing specific shipping method
                break; // we stop the loop
            }
        }
        return $rates;
    }
    

    So your code should work too (if you have set the correct IDs)

    BUT you need (after saving your code to the function.php file of your active theme):

    1. To remove all cart items that are remaining in cart when testing.

    2. To refresh the shipping caches:
      To do it, you can go in a shipping zone and disable one "flat rate" (for example) and "save". Then re-enable that "flat rate" and "save". You are done.

    Now you can test again and it should work