How to hide shipping methods for specific shipping class in WooCommerce

Are you finding ways to hide shipping methods when Free Shipping is enabled? Trying to hide shipping methods for Shipping Classes ?

There are many plugins for this which will cost you $$$.

Here we will discuss, how you can do it free.

Open your themes functions.php file and insert the below code

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 = 100;

    // 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;
}

Replace 100 with your original class id

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).

Replace flat_rate:7, local_pickup:3 with your shipping methods name that you would like to hide.

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

enter image description here

Leave a Reply

Your email address will not be published.

*

code