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.

WooCommerce: Disable Free Shipping if a specific Shipping Class is in the CartWooCommerce: Disable Free Shipping if a specific Shipping Class is in the Cart
WooCommerce: Disable Free Shipping if a specific Shipping Class is in the Cart

PHP Snippet: Disable Free Shipping Rate if WooCommerce Cart Contains Product with Specific Shipping Class

/**
 * @snippet       Disable Free Shipping if Cart has Shipping Class (WooCommerce 2.6+)
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 4.0
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */
 
add_filter( 'woocommerce_package_rates', 'businessbloomer_hide_free_shipping_for_shipping_class', 10, 2 );
  
function businessbloomer_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:

Clear Customer Sessions – WooCommerce System Status Tools

WooCommerce: How to Find Shipping Class ID

WooCommerce 2.6+: Find Shipping Class IDWooCommerce 2.6+: Find Shipping Class ID
WooCommerce 2.6+: Find Shipping Class ID

WooCommerce: How to Find Shipping Method ID

Find Shipping Method Name in WooCommerce 2.6+Find Shipping Method Name in WooCommerce 2.6+
Find Shipping Method Name in WooCommerce 2.6+
Share:

Leave a Reply