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
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

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 this snippet?

You can place PHP snippets at the bottom of your child theme functions.php file (delete "?>" if you have it there). CSS, on the other hand, goes in your child theme style.css file. Make sure you know what you are doing when editing such files - if you need more guidance, please take a look at my free video tutorial "Where to Place WooCommerce Customization?"

Does this snippet (still) work?

Please let me know in the comments if everything worked as expected. I would be happy to revise the snippet if you report otherwise (please provide screenshots). I have tested this code with Storefront theme, the WooCommerce version listed above and a WordPress-friendly hosting on PHP 7.3.

If you think this code saved you time & money, feel free to join 14,000+ WooCommerce Weekly subscribers for blog post updates or 250+ Business Bloomer supporters for 365 days of WooCommerce benefits. Thank you in advance :)

Need Help with WooCommerce?

Check out these free video tutorials. You can learn how to customize WooCommerce without unnecessary plugins, how to properly configure the WooCommerce plugin settings and even how to master WooCommerce troubleshooting in case of a bug!

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.

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

  1. 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

  2. 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

  3. Is this still working with Woo 3.9.2?

    1. Yep. Got issues?

  4. 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?

  5. 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!

  6. 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

  7. 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? Support? Leave your Comment Now!
_____

If you are writing code, please wrap it between shortcodes: [php]code_here[/php]. Failure to complying with this (as well as going off topic, not writing in English, etc.) will result in comment deletion. 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 BloomerArmada to get blog comment reply priority, ask me 1-to-1 WooCommerce questions and enjoy many more perks. Thank you :)

Your email address will not be published.