Hide shipping methods for specific shipping class in WooCommerce

Update 2019: You should try instead this shorter, compact and effective way:

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 to find
    $class = 92;
    
    // HERE define the shipping method to hide
    $method_key_id = 'flat_rate:7';
    
    // Checking in cart items
    foreach( $package['contents'] as $item ){
        // If we find the shipping class
        if( $item['data']->get_shipping_class_id() == $class ){
            unset($rates[$method_key_id]); // Remove the targeted method
            break; // Stop the loop
        }
    }
    return $rates;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.

Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your “flat rates” shipping methods.

Related: Hide shipping methods for specific shipping classes in WooCommerce

To find the shipping methods IDs and the shipping classes IDs see below…


Update for many different shipping methods (related to your comments):

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 to find
    $class = 92;

    // HERE define the shipping methods you want to hide
    $method_key_ids = array('flat_rate:7', 'local_pickup:3');

    // Checking in cart items
    foreach( $package['contents'] as $item ) {
        // If we find the shipping class
        if( $item['data']->get_shipping_class_id() == $class ){
            foreach( $method_key_ids as $method_key_id ){
                unset($rates[$method_key_id]); // Remove the targeted methods
            }
            break; // Stop the loop
        }
    }
    return $rates;
}

Tested and works…


Finding the shipping class ID.

  1. In the database under wp_terms table:

Search for a term name or a term slug and you will get the term ID (the shipping class ID).

  1. On Woocommerce shipping settings editing a “Flat rate”, with your browser html inspector tool, inspect a shipping Class rate field like:

enter image description here

In the imput name attribute you have woocommerce_flat_rate_class_cost_64. So 64 is the ID for the shipping class.


Get the shipping method rate ID:

To get the related shipping methods rate IDs, something like flat_rate:12, inspect with your browser code inspector each related radio button attribute value like:

enter image description here

Leave a Comment