Home » WooCommerce: Hide Shipping By Shipping Class

WooCommerce: Hide Shipping By Shipping Class

by Tutor Aspire

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 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
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 6
 * @donate $9     https://www.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:

Clear Customer Sessions – WooCommerce System Status Tools

WooCommerce: How to Find Shipping Class ID

WooCommerce 2.6+: Find Shipping Class ID
WooCommerce: 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

You may also like