How to hide specific shipping method for a specific shipping class in WooCommerce

Default shipping options in WooCommerce leave a lot to be desired. Such is the case with setting up specific scenarios like hiding a specific shipping method – but only for a specified shipping class. In this case, a client had multiple shipping methods active and wanted to remove just one of them based on a shipping class.

First we need to find the shipping class and shipping method ID’s. 

How to find shipping class and method ID's

Shipping Class

The easiest way to find a shipping class ID is to open WooCommerce Settings and navigate to Shipping > Shipping Classes section and Right click > Inspect the slug of the shipping class you wish to hide. The number in the brackets (in this case 3833) is the shipping class ID. 

Shipping Method

To find shipping method ID in WooCommerce, navigate to the checkout page and Right click > Inspect the shipping method in question. You’ll find shipping method ID under “value”. 
 

 

Hide shipping method for a specific shipping class

Here is the snippet to add to functions.php file. Make sure to replace the shipping method and shipping class ID in the code before updating your functions.php file.


/* Removes specified shipping method for specified shipping class */

add_filter( 'woocommerce_package_rates', 'hide_shipping_method_for_specified_shipping_class', 10, 2 );
function hide_shipping_method_for_specified_shipping_class( $rates, $package )
{
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // Replace with your own shipping class here
    $class = 1111;
    
    // Replace with your own shipping method
    $method_key_id = 'flat_rate:1';
    
    // Go through cart items
    foreach( $package['contents'] as $item ){
        // When shipping class is found
        if( $item['data']->get_shipping_class_id() == $class ){
            unset($rates[$method_key_id]); // Remove shipping method
            break; 
        }
    }
    return $rates;
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top