Hide Specific Shipping Methods When a Product Category Is in the Cart
Remove selected WooCommerce shipping rates whenever the cart contains a product from a chosen product category.
Some products need special delivery handling. For example, a fragile product category may require freight shipping, so the store should hide free_shipping and flat_rate whenever one of those products is in the cart.
Add this snippet to a child theme’s functions.php file or a code snippets plugin. The method IDs must match the IDs returned by your shipping zones, so inspect the checkout HTML or temporarily log $rate->get_method_id() if needed.
The snippet
add_filter( 'woocommerce_package_rates', function( $rates, $package ) { $restricted_category = 'fragile-items'; $category_in_cart = false;
foreach ( $package['contents'] as $item ) { $product_id = $item['product_id'];
if ( has_term( $restricted_category, 'product_cat', $product_id ) ) { $category_in_cart = true; break; } }
if ( ! $category_in_cart ) { return $rates; }
$hidden_methods = array( 'free_shipping', 'flat_rate' );
foreach ( $rates as $rate_id => $rate ) { if ( in_array( $rate->get_method_id(), $hidden_methods, true ) ) { unset( $rates[ $rate_id ] ); } }
return $rates;}, 20, 2 );Choosing the correct method ID
The filter receives rates after WooCommerce has matched the customer’s shipping zone. A rate key may look like flat_rate:3, but get_method_id() returns the stable method ID, such as flat_rate or free_shipping. That is why the snippet compares the method ID rather than the full array key.
Shipping packages are calculated separately. The code checks $package['contents'], so it applies only to the package containing the restricted product. If your store splits packages by shipping class or destination, this behavior is usually preferable to hiding rates globally.
Keep a fallback available
Do not hide every available method unless you also add a replacement rate. If the category removes the only rate, customers may see a checkout error or be unable to complete the order. For a hard restriction, consider adding a dedicated shipping method such as local_pickup or a carrier service that supports the product.
For a related checkout control, see how to set a minimum order amount and how to apply an automatic cart discount. The WooCommerce hooks reference is useful when checking the exact shipping-rate hook available in your installed version.