/**
* Check if the cart has product with a certain Shipping Class
* @param string $slug the shipping class slug to check for
* @return bool true if a product with the Shipping Class is found in cart
*/
function cart_has_product_with_shipping_class( $slug ) {
global $woocommerce;
$product_in_cart = false;
// start of the loop that fetches the cart items
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
$terms = get_the_terms( $_product->id, 'product_shipping_class' );
if ( $terms ) {
foreach ( $terms as $term ) {
$_shippingclass = $term->slug;
if ( $slug === $_shippingclass ) {
// Our Shipping Class is in cart!
$product_in_cart = true;
}
}
}
}
return $product_in_cart;
}
//For example, to check for the Shipping Class ‘free-shipping’, use this:
if ( cart_has_product_with_shipping_class( 'free-shipping' ) ) {
// Yes, the cart has a product with the 'free-shipping' Shipping Class.
} else {
// The cart does NOT have a product with the 'free-shipping' Shipping Class.
}