Create Custom Menu in WordPress Dashboard
Complete tutorial on create custom menu in wordpress dashboard. Discover practical examples, implementation tips, and expert advice for WordPress and WooCo
Read More โVerify if products from specific category exist in WooCommerce cart using woocommerce_before_cart_contents action hook and has_term function. Loop through cart items with get_cart method, check product categories using has_term with product_cat taxonomy, implement conditional logic for category-specific promotions, apply special discounts or free shipping based on categories, display custom messages when target category found, restrict checkout for incompatible categories, and create personalized shopping experiences based on product category presence.
If you want to identify whether a product from a specific category is in the cart on your WooCommerce store, you can easily achieve this using the woocommerce_before_cart_contents hook. This allows you to customize the cart experience based on the categories of products added.
Step-by-Step Guide to Check Product Category
Use the following code to check if a product from a particular category is in the WooCommerce cart:
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 category slug
$category_found = false;
// Get cart items
$cart_items = WC()->cart->get_cart();
// Loop through 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 category
if (has_term($category_slug, 'product_cat', $product_id)) {
$category_found = true;
break;
}
}
// Output message based on category presence
if ($category_found) {
echo 'This product category is in the cart.';
} else {
echo 'This product category is not in the cart.';
}
}
What Happens in This Code?
When you implement this code, it will check whether any products in the cart belong to a particular category. Simply replace 'your-category-slug' with the slug of your desired product category. If a product in the cart belongs to that category, the message will indicate its presence.
Enhancing the Code for Custom Actions
Adding This Code to Your Site
To make this work, you need to add the code to your theme’s functions.php file or create a custom plugin for better portability. Make sure this code is included in a location that will execute on the cart page.
Additional Resources

Search our archives or reach out to our team for solutions and expert advice.