WooCommerce: Check if Product Category is in the Cart

We already studied how to detect if a product ID is in the cart – but if you take a look at the comments many of you were asking how to detect product categories.

So, today we’ll do exactly that. You can disable shipping rates, payment gateways, you can print messages, you can apply coupon programmatically… there are lots of things you can do “conditionally”, based on whether a given product category is in the Cart or not.

Check if Product Category is in the Cart – WooCommerce

PHP Snippet: Check if Product Category is inside the Cart – WooCommerce

/**
 * @snippet       Check if Product Category is in the Cart - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */

add_action( 'woocommerce_before_cart', 'bbloomer_check_category_in_cart' );

function bbloomer_check_category_in_cart() {

   // Set $cat_in_cart to false
   $cat_in_cart = false;

   // Loop through all products in the Cart
   foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

      // If Cart has category "download", set $cat_in_cart to true
      if ( has_term( 'download', 'product_cat', $cart_item['product_id'] ) ) {
         $cat_in_cart = true;
         break;
      }
   }

   // Do something if category "download" is in the Cart
   if ( $cat_in_cart ) {

      // For example, print a notice
      wc_print_notice( 'Category Downloads is in the Cart!', 'notice' );

      // Or maybe run your own function...
      // ..........

   }

}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: How to Fix the “Cart is Empty” Issue
    For some reason, sometimes you add products to cart but the cart page stays empty (even if you can clearly see the cart widget has products in it for example). But don’t worry – it may just be a simple cache issue (and if you don’t know what cache is that’s no problem either) or […]
  • WooCommerce: “You Only Need $$$ to Get Free Shipping!” @ Cart
    This is a very cool snippet that many of you should use to increase your average order value. Ecommerce customers who are near the “free shipping” threshold will try to add more products to the cart in order to qualify for free shipping. It’s pure psychology. Here’s how we show a simple message on the […]
  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Weight-Based Shipping Methods
    With WooCommerce you get 3 default shipping methods: Flat Rate, Free Shipping, Local Pickup. For each one you can define a cost, however there is no way to set up some “weight” restrictions. So, what if you want to display a rate for orders below 10 kg, and another shipping rate for orders above that […]
  • WooCommerce: Hide Shipping Method If Shipping Class Is In The Cart
    Our goal is to check if a Product with a specific Shipping Class is in the Cart, and consequently disabling a shipping rate such as Free Shipping if this is true. This is super useful when there are multiple items in the cart and you don’t want to give free shipping for certain orders for […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

17 thoughts on “WooCommerce: Check if Product Category is in the Cart

  1. Thanks for the code!

    Any idea how can we add multiple categories instead of only 1?

    Many Thanks

    1. Hello Irvin, has_term() also allows for an array of categories, so you could do this:

      if ( has_term( array( 'download', 'tables', 'chairs' ), 'product_cat', $cart_item['product_id'] ) )
  2. Hello, congratulations for the site, always very useful.
    I wanted to make a change to your code by placing a free product according to the category.
    I tried this but it doesn’t work:

    add_action('woocommerce_before_cart', 'bbloomer_check_category_in_cart');
     
    function bbloomer_check_category_in_cart() {
     
    // Set $cat_in_cart to false
    $cat_in_cart = false;
     
    // Loop through all products in the Cart        
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
     
        // If Cart has category "download", set $cat_in_cart to true
        if ( has_term( 'trattamenti', 'product_cat', $cart_item['product_id'] ) ) {
            $cat_in_cart = true;
            break;
        }
    }
       
    // Do something if category "download" is in the Cart      
    if ( $cat_in_cart ) {
    
    add_action( 'template_redirect', 'add_product_to_cart' );
    function add_product_to_cart() {
    	if ( ! is_admin() ) {
    		$product_id = 53425; //replace with your own product id
    		$found = false;
    		//check if product already in cart
    		if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
    			foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
    				$_product = $values['data'];
    				if ( $_product->get_id() == $product_id )
    					$found = true;
    			}
    			// if product not found, add it
    			if ( ! $found )
    				WC()->cart->add_to_cart( $product_id );
    		} else {
    			// if no products in cart, add it
    			WC()->cart->add_to_cart( $product_id );
    		}
    	}
    }
     
    }
     
    }

    Thanks

    1. Your code has many errors, sorry but that’s custom troubleshooting work

  3. Still works, is it possible to make it work on checkout page too ?

    Thanks awesome snippet

    1. Thank you. This works on the Checkout page as well

  4. Is this still working with Woo 3.9.2?

    1. Yep. Got issues?

  5. And on the contrary, as it would be if instead of indicating that “this category” should be in the cart, do you want to exclude a category?

  6. Hye Rodolfo Melogli,
    I am trying to create a functionality that if i add a product to cart and then after if i want to add a another product to cart having low price then previous product it will give me a warning msg in popup. Will you please help me regarding this?
    I am new to php and not getting any clue from anywhere.

    1. Arun, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  7. Code works fine!

    Few questions:

    1. What if I want to add 3 categories to the function? So a product has to be in one of the 3 categories.

    2. I want to combine the categories with a minimal subtotal that is in the cart.

    So basically I want the message to appear when:
    A product in one of the 3 specified categories is in the cart AND the subtotal is less than 699.

    Hope you can help me out.

    1. Kevin, thanks so much for your comment! Yes, this is possible – but unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  8. I used this code but nothing happens. If I change get_id() to just id then it works. Even though I know id is deprecated and Woo recommends using get_id()

    So, I changed this line
    if ( has_term( ‘download’, ‘product_cat’, $product->get_id() ) ) {
    to
    if ( has_term( ‘download’, ‘product_cat’, $product->id ) ) {

    Odd.

    1. I have Woo 3.2.2

      1. Not sure Vuster, it works perfectly on my test website on Woo 3.2.2 ๐Ÿ™‚

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *