76
Our goal is to check if a Product with a specific Shipping Class is in the Cart, and consequently disabling a shipping rate such as Free Shipping if this is true.
This is super useful when there are multiple items in the cart and you don’t want to give free shipping for certain orders for example.
PHP Snippet: Disable Free Shipping Rate if WooCommerce Cart Contains Product with Specific Shipping Class
/**
* @snippet Disable Free Shipping if Cart has Shipping Class
* @how-to Get tutoraspire.com FREE
* @author Tutor Aspire
* @testedwith WooCommerce 6
* @donate $9 https://tutoraspire.com
*/
add_filter( 'woocommerce_package_rates', 'tutoraspire_hide_free_shipping_for_shipping_class', 9999, 2 );
function tutoraspire_hide_free_shipping_for_shipping_class( $rates, $package ) {
$shipping_class_target = 15; // shipping class ID (to find it, see screenshot below)
$in_cart = false;
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
if ( $values[ 'data' ]->get_shipping_class_id() == $shipping_class_target ) {
$in_cart = true;
break;
}
}
if ( $in_cart ) {
unset( $rates['free_shipping:8'] ); // shipping method with ID (to find it, see screenshot below)
}
return $rates;
}
Shipping Rates Not Hiding After Implementing PHP?
You probably need to clear the customer sessions: