You can create a custom function in WooCommerce that checks the cart items for the presence of specific shipping classes, and enables or disables free shipping based on their presence. The code snippet below can be used if you want to enable/disable free shipping. Read the notes on the bottom, how you can adopt this snippet to other shipping methods.
add_filter( 'woocommerce_shipping_free_shipping_is_available', 'shipping_classes_free_shipping' );
function shipping_classes_free_shipping( $is_available ) {
// The IDs of the shipping classes that should disable/enable free shipping
$disable_shipping_class_id = 1;
$enable_shipping_class_id = 2;
// Get the cart contents
$cart = WC()->cart->get_cart();
// Check if the disable shipping class is present in the cart
$disable_shipping_class_present = false;
foreach ( $cart as $item ) {
if ( $item['data']->get_shipping_class_id() == $disable_shipping_class_id ) {
$disable_shipping_class_present = true;
break;
}
}
// Check if the enable shipping class is present in the cart
$enable_shipping_class_present = false;
foreach ( $cart as $item ) {
if ( $item['data']->get_shipping_class_id() == $enable_shipping_class_id ) {
$enable_shipping_class_present = true;
break;
}
}
// If both shipping classes are present, enable free shipping
if ( $disable_shipping_class_present && $enable_shipping_class_present ) {
return true;
}
// If only the disable shipping class is present, disable free shipping
if ( $disable_shipping_class_present && ! $enable_shipping_class_present ) {
return false;
}
// If neither shipping class is present, return the original availability value
return $is_available;
}
Notes
Make sure to replace $disable_shipping_class_id = 1
and $enable_shipping_class_id = 2
with the actual IDs of the shipping classes that you want to check for. To find out the ID’s read this article: https://rudrastyh.com/woocommerce/how-to-get-shipping-class-id.html.
The woocommerce_shipping_free_shipping_is_available
hook determines what shipping method you are enabling or disabling.
You can add this code snippet to your WordPress child theme’s functions.php file, or use a plugin such as Code Snippets to add it to your site.