How to Detect Product Categories in WooCommerce Cart

Want to check if a product from a specific category is in the WooCommerce cart? You can do this easily using the woocommerce_before_cart_contents action hook, which triggers before cart items are displayed. Below is a practical example of how to achieve it:

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

function check_product_category_in_cart() {
    $category_slug = 'your-category-slug'; // Replace with your actual category slug
    $category_found = false;

    // Get items from the cart
    $cart_items = WC()->cart->get_cart();

    // Loop through each item
    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];

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

    // Display message based on result
    if ($category_found) {
        echo 'The category is in the cart.';
    } else {
        echo 'The category is not in the cart.';
    }
}

Just update 'your-category-slug' to the correct slug for the category you want to target. Add this snippet to your theme’s functions.php or a custom plugin. It will run whenever the cart page loads and inform whether a matching product category is in the cart.

 

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.