This is a function for WooCommerce. It checks to see if there is a product with a certain “Shipping Class” in the cart. It takes one parameter, the slug of the Shipping Class. The function returns true if a product with the Shipping Class is found in the cart. Otherwise, it returns false.
/** * 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
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. }
Raman
August 3rd, 2016 at 5:04 am
nice code works for me thanks 🙂
Rayaan
September 4th, 2017 at 5:22 am
thanks for this code snippet, works like a charme
Kalliopi
September 28th, 2017 at 4:29 am
Really usefull snippet, thanks!
Sasa
November 28th, 2017 at 12:30 pm
Great code. Thank you for this.
Sandeep Tete
January 19th, 2018 at 5:33 am
My case was to disable cod if a shipping class if found in cart….worked perfectly…God Bless
Sandeep Tete
January 19th, 2018 at 5:34 am
My code
BWeb
March 30th, 2019 at 7:53 pm
Great code and instructions. I’m looking for some code I can’t figure out and was wondering if anyone has an answer to this. I need to prevent the display of certain text if no items in the cart have a shipping class.
Condition: No products in the cart have a shipping class.
Function/Result: Hide display of woocommerce-shipping-destination and woocommerce-shipping-calculator.
I’m sure this is probably easy for someone who actually writes php.
Thanks.