wgardner
2/5/2019 - 3:36 PM

Check if any product in cart has a certain Shipping Class

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;
}


//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.
 
}