Check Product Category in WooCommerce Cart
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
- Customize the message displayed based on the presence of the category.
- Use this check to apply specific discounts, shipping conditions, or checkout rules when the category is found in the cart.
- Modify the logic to suit your store’s specific needs, such as offering special deals for certain categories of products.
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
- WooCommerce Cart Notices – Learn how to display custom messages in the WooCommerce cart.
- WooCommerce Shortcodes – Discover useful shortcodes to enhance your store.