Hide a Shipping Method for a Shipping Class
Removes a shipping method, such as local pickup or express delivery, when the cart contains a product from a specific shipping class (for example bulky items).
Opens WPIDE on
Code
add_filter( 'woocommerce_package_rates', function ( $rates, $package ) {
$shipping_class = 'bulky'; // Shipping class slug.
$method = 'free_shipping'; // Method ID to hide when the class is in the cart.
$found = false;
foreach ( (array) $package['contents'] as $item ) {
if ( isset( $item['data'] ) && $item['data']->get_shipping_class() === $shipping_class ) {
$found = true;
break;
}
}
if ( ! $found ) {
return $rates;
}
foreach ( $rates as $id => $rate ) {
if ( $rate->get_method_id() === $method ) {
unset( $rates[ $id ] );
}
}
return $rates;
}, 10, 2 );
Notes
Set $shipping_class to the class slug from WooCommerce > Settings > Shipping > Classes and $method to the method ID (flat_rate, local_pickup, free_shipping).
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.