Created
August 26, 2017 00:43
-
-
Save easaw/3ce94387285d82fc47fa548163bd27f6 to your computer and use it in GitHub Desktop.
Check if the Woocommerce cart has product with a certain Shipping Class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* From https://isabelcastillo.com/woocommerce-check-shipping-class | |
* 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; | |
} | |
/* | |
* USAGE: | |
*/ | |
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. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment