Home » WooCommerce: Check if Product Category is in the Cart

WooCommerce: Check if Product Category is in the Cart

by Tutor Aspire

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 tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 5
 * @donate $9     https://www.tutoraspire.com
 */

add_action( 'woocommerce_before_cart', 'tutoraspire_check_category_in_cart' );

function tutoraspire_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...
      // ..........

   }

}

You may also like