WooCommerce: Check if Product Category is in the Cart

To check if a specific product category is in the cart during the `woocommerce_before_cart` action hook, you can use a similar approach as in the previous answer. However, in this case, you need to use the `woocommerce_before_cart_contents` action hook, which fires before the cart items are displayed on the cart page. Here’s how you can achieve this:

 

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

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

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

    // Loop through the cart items
    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);

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

    if ($category_found) {
        // Category is in the cart, do something
        echo 'The category is in the cart.';
    } else {
        // Category is not in the cart, do something else
        echo 'The category is not in the cart.';
    }
}

 

Replace `’your-category-slug’` with the desired category slug you want to check. This code will run when the cart page is loaded, and it will check if any product in the cart belongs to the specified category. If the category is found in the cart, it will display “The category is in the cart.” If the category is not in the cart, it will display “The category is not in the cart.”

Remember to place this code snippet in your theme’s `functions.php` file or in a custom plugin to ensure it runs properly on your WooCommerce store.

Related Blogs

How To Limit Search To Only Post Titles?

I added a text field to the posts filter form and I use s= parameter to make the search work. But how to search only in the title of the post (not in the content)? how to limit search to post titles? How to search only by Post Title?

Shortcodes included with WooCommerce

WooCommerce comes with several shortcodes that you can use to display various elements and functionalities on your WordPress website. These shortcodes allow you to customize the appearance and layout of your WooCommerce store. Here are some of the essential shortcodes included with WooCommerce:

Request A Quote

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.