Hide Shipping Method When Cart Contains Shipping Class

A popular request over the last several months, some items simply do not qualify for one of your shipping methods. For example, you could not send large scale pieces of furniture via regular services such as UPS, so you may opt to remove this choice when a customer purchases small items in addition to a furniture item. The best way to go about this is to assign your large pieces of furniture a special shipping class that denotes it is too large for regular shipping.

The code snippet below removes the ‘Free Shipping’ method from the list of available choices if items belonging to the shipping classes 1111, 2232, and 4235 (all ID numbers) are in the cart.

add_filter( 'woocommerce_package_rates', 'hide_shipping_when_class_is_in_cart', 10, 2 );

function hide_shipping_when_class_is_in_cart( $rates, $package ) { 
	// shipping class IDs that need the method removed 
	$shipping_classes = array(1111,2232,4235);
	$if_exists = false;

	foreach( WC()->cart->cart_contents as $key => $values )
		if( in_array( $values[ 'data' ]->get_shipping_class_id(), $shipping_classes ) )
			$if_exists = true;

	if( $if_exists ) unset( $rates['free_shipping'] );

	return $rates;
}
  • Was this article helpful ?
  • yes   no