• I found this code and I’m using it to hide the cheapest shipping method when any product from a certain shipping class is in the cart. This worked so far, but the exception was only 1 shipping class.

    Now I wanted to add 2 more shipping classes to the mandatory list, and it doesn’t work. Only the first named class slug is recognized. Is there a way to workaround this?

    The goal is to hide shipping method “flat_rate:2” when any product from any of the 3 shipping classes is added to the cart: shipping class slugs “caixa”, “trajes” and “kits”.

    The code is this:

    add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
    function hide_shipping_method_based_on_shipping_class( $rates, $package )
    {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        // HERE define your shipping class SLUG
        $class_slug = 'large';
    
        // HERE define the shipping method to hide
        $method_key_id = 'flat_rate:7';
    
        // Checking in cart items
        foreach( WC()->cart->get_cart() as $cart_item ){
            // If we find the shipping class
            if( $cart_item['data']->get_shipping_class() == $class_slug ){
                unset($rates[$method_key_id]); // Remove the targeted method
                break; // Stop the loop
            }
        }
        return $rates;
    }

    Cheers

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Hiding shipping method according to shipping class’ is closed to new replies.