WooCommerce provides support for filtering shipping methods based on country out of the box. For more advanced filtering a code snippet or a plugin is needed.
This tutorial shows how to disable a shipping method based on a product category. For example, you might have a product category for large kitchen appliances which may be shipped only with the Freight shipping method.
The following code disables “Economy” shipping method when there are products from the Kitchen Appliances category in the cart. The code needs to be added to functions.php file in your theme or with Code Snippets.
Feel free to change “Economy” and “Kitchen Appliances” (lines 9 and 22) in the code to suit your needs.
Add this code snippet:
/**
* Filter shipping methods in the checkout
*/
add_filter( 'woocommerce_package_rates', 'wooelements_filter_shipping_methods', 10, 2 );
function wooelements_filter_shipping_methods( $rates, $package ) {
// Find Economy shipping method
$economy_shipping_method_key = FALSE;
foreach ( $rates as $rate_key => $rate ) {
if ( is_object( $rate ) && method_exists( $rate, 'get_label' ) && $rate->get_label() === "Economy" ) {
$economy_shipping_method_key = $rate_key;
}
}
// Go through all products and check their category
if ( $economy_shipping_method_key !== FALSE ) {
$kitchen_appliances_found = FALSE;
foreach ( $package['contents'] as $key => $item ) {
$categories = get_the_terms( $item['product_id'], 'product_cat' );
if ( $categories && ! is_wp_error( $categories ) && is_array( $categories ) ) {
foreach ( $categories as $category ) {
if ( "Kitchen Appliances" === $category->name ) {
$kitchen_appliances_found = TRUE;
}
}
}
}
// Kitchen appliances has been found, disable the Economy shipping
if ( $kitchen_appliances_found === TRUE ) {
unset( $rates[$economy_shipping_method_key] );
}
}
return $rates;
}
Easier Way
If you have many shipping methods with different restrictions, it might be easier to use a plugin. We have published WooCommerce Conditional Shipping Pro which makes it very easy to restrict shipping methods directly from the WooCommerce settings. You can add conditions such as product category, shipping class, weight, subtotal and much more.