Check if a Product Category is in the WooCommerce Cart

If you’re looking to check if a product from a particular category is in the WooCommerce cart, you can use the woocommerce_before_cart_contents hook. This gives you control over the cart based on the products in specific categories.

 

Steps to Check Product Category

Here’s the code that checks if a product from a specific category is in the cart:

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

function check_product_category_in_cart() {
    $category_slug = 'your-category-slug'; // Change to your category slug
    $category_found = false;

    $cart_items = WC()->cart->get_cart();

    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);

        if (has_term($category_slug, 'product_cat', $product_id)) {
            $category_found = true;
            break;
        }
    }

    if ($category_found) {
        echo 'Product from the category is in the cart.';
    } else {
        echo 'No products from this category in the cart.';
    }
}

What the Code Does

The code loops through each item in the cart and checks if it belongs to the specified category. Change the category slug to match your product category. The message changes depending on whether the category is in the cart or not.

Advanced Use Cases

  • Use this check to add special discounts if products from certain categories are added.
  • Apply special shipping methods or conditions when specific categories are in the cart.

Adding the Code

You can add the code in your theme’s functions.php file or create a custom plugin for greater portability.

Further Resources

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.