To determine whether a specific product category exists in the WooCommerce cart, use the woocommerce_before_cart_contents
hook. This allows you to run a function just before cart items are rendered. Here’s how you can set it up:
add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart'); function check_product_category_in_cart() { $category_slug = 'your-category-slug'; // Enter the category slug you're targeting $category_found = false; $cart_items = WC()->cart->get_cart(); foreach ($cart_items as $key => $item) { $product_id = $item['product_id']; if (has_term($category_slug, 'product_cat', $product_id)) { $category_found = true; break; } } if ($category_found) { echo 'The category is in the cart.'; } else { echo 'The category is not in the cart.'; } }
Replace 'your-category-slug'
with your actual category slug. You can insert this snippet into your active theme’s functions.php
file or your custom plugin. It checks the cart contents and prints a message depending on whether the target category is present.