WooCommerce: Check If Product Belongs to Category / Tag

We’ve studied “conditional logic” extensively over the previous Business Bloomer posts. In today’s spin-off, I want to clarify how you can check if a given product belongs to a category, tag or custom taxonomy because this is one of the most used conditional logic scenarios.

It’s important to know that a product can be inside the “loop” (e.g. the shop page or a list of products), alternatively you may be on the single product page or have the product unique ID, or even you can check if a product category is inside the Cart. Finally, you can even run the product category check within an Order or an Order Email.

Either way, the function is always the same. You simply need to understand how to use it. Enjoy!

Meet the has_term() WordPress function

WordPress comes to the rescue with the has_term() function, which accepts 3 parameters:

  1. The term (category, tab, custom term) name, term ID, slug or array of them
  2. The taxonomy name (default or custom)
  3. The post ID or post object, in case you don’t want to use the “current post”

It basically goes like this: you define a term you want to check against the post object e.g. “Rock”, you specify the default or custom taxonomy name (in the Jazz example it could be you’re using a “Music” custom taxonomy) and finally you may specify the post ID:

if ( has_term( 'rock', 'music', 26 ) ) {
    // do something if post 26 belongs to Rock Music
}

Easy peasy. Now it’s time to apply this to WooCommerce and see where it could come in handy. WooCommerce comes already with custom taxonomies: “product_cat” for product categories and “product_tag” for product tags. That’s all we need to use.

WooCommerce: check if current product belongs to product category @ Single Product Page

This is the easiest case scenario. You’re customizing the single product page and want to show a specific banner in case the current product belongs to a certain category.

The good thing is that we are on the single product page and therefore we know the “current post” exists and we don’t need the third has_term() parameter.

I’ve picked the woocommerce_before_single_product hook to display the banner above the single product template, but feel free to chose any other single product page hooks. Code goes like this:

add_action( 'woocommerce_before_single_product', 'bbloomer_print_banner_if_product_belongs_to_category_tables' );

function bbloomer_print_banner_if_product_belongs_to_category_tables() {
   if ( has_term( 'tables', 'product_cat' ) ) {
      echo '<img src="banner.png">';
   }
}

Only if the single product we’re looking at belongs to the “tables” category, the image will display. Otherwise, nothing will happen.

WooCommerce: check if current product belongs to product tag @ Single Product Page

Similarly, you can check the current product against a given product_tag:

add_action( 'woocommerce_before_single_product', 'bbloomer_print_banner_if_product_belongs_to_tag_red' );

function bbloomer_print_banner_if_product_belongs_to_tag_red() {
   if ( has_term( 'red', 'product_tag' ) ) {
      echo '<img src="banner2.png">';
   }
}

WooCommerce: check if current product belongs to product category @ Shop Page

Let’s complicate things.

We’re now in the Shop page, or in a product list section generated by a shortcode. That’s called the “loop”. In this case, you have multiple products in the same page, so we can’t really use the same method as above as the “current post” won’t be a product ID – instead it will be the current page ID.

We therefore need to “calculate” the ID based on the position we’re inside the “loop”. That’s easier coded than said actually.

So, let’s try to print a message under EVERY product in the Shop page that belong to a given category e.g. “Chairs”. I’ve used the woocommerce_after_shop_loop_item but feel free to pick any other shop hooks from my visual hook guide.

As you can see inside the snippet, I first need to find out the “loop product ID” because this needs to run for each product in the loop, and after that I can go back using the has_term() conditional:

add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_print_message_if_product_belongs_to_category_chairs' );

function bbloomer_print_message_if_product_belongs_to_category_chairs() {
   global $product;
   $product_id = $product->get_id();
   if ( has_term( 'chairs', 'product_cat', $product_id ) ) {
      echo 'A message about chairs';
   }
}

WooCommerce: check if current product belongs to product tag @ Shop Page

No comment.

add_action( 'woocommerce_after_shop_loop_item', 'bbloomer_print_message_if_product_belongs_to_tag_yellow' );

function bbloomer_print_message_if_product_belongs_to_tag_yellow() {
   global $product;
   $product_id = $product->get_id();
   if ( has_term( 'yellow', 'product_tag', $product_id ) ) {
      echo 'A message about yellow products';
   }
}

WooCommerce: check if a product ID belongs to product category

Let’s say you are outside the loop and not on the single product page. That means you have no “current product” to deal with, no global $product you can call, and you’re stuck.

Thankfully, the has_term() function accepts the post ID as third parameter so you can run your conditional check even on the Homepage, inside a shortcode, inside a WooCommerce order email, and so on.

You simply need to specify the ID you desire.

In this case study I wish to display something in the footer if product ID 59 belongs to a certain category. It could be for a site-wide advertising banner for example

add_action( 'wp_footer', 'bbloomer_print_message_if_product_ID_belongs_to_category_lamps' );

function bbloomer_print_message_if_product_ID_belongs_to_category_lamps() {
   if ( has_term( 'lamps', 'product_cat', 59 ) ) {
      echo '<p>Product ID 59 belongs to Lamps</p>';   
   }
}

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 Visual Hook Guide: Single Product Page
    Here’s a visual hook guide for the WooCommerce Single Product Page. This is part of my “Visual Hook Guide Series“, through which you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can copy/paste). If you like this guide and it’s helpful to you, let me know in the comments! […]
  • WooCommerce: Disable Variable Product Price Range $$$-$$$
    You may want to disable the WooCommerce variable product price range which usually looks like $100-$999 when variations have different prices (min $100 and max $999 in this case). With this snippet you will be able to hide the highest price, and add a “From: ” prefix in front of the minimum price. At the […]
  • WooCommerce: Hide Price & Add to Cart for Logged Out Users
    You may want to force users to login in order to see prices and add products to cart. That means you must hide add to cart buttons and prices on the Shop and Single Product pages when a user is logged out. All you need is pasting the following code in your functions.php (please note: […]
  • WooCommerce Visual Hook Guide: Archive / Shop / Cat Pages
    I’ve created a visual HTML hook guide for the WooCommerce Archive Page (which is the same page for the Shop, Category, Tag pages). This visual guide belongs to my “Visual Hook Guide Series“, that I’ve put together so that you can find WooCommerce hooks quickly and easily by seeing their actual locations (and you can […]
  • WooCommerce: Hide Prices on the Shop & Category Pages
    Interesting WooCommerce customization here. A client of mine asked me to hide/remove prices from the shop page and category pages as she wanted to drive more customers to the single product pages (i.e. increasing the click-through rate). As usual, a simple PHP snippet does the trick. I never recommend to use CSS to “hide” prices, […]

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

8 thoughts on “WooCommerce: Check If Product Belongs to Category / Tag

  1. You can also check for multiple categories or tags by using `array()` like this:

    function bbloomer_print_banner_if_product_belongs_to_category_tables() {
       if ( has_term( array( 'table-1', 'table-2', 'table-3' ), 'product_cat' ) ) {
          echo '<img src="banner.png">';
       }
    }
  2. By default woocommerce related products displays each product of the same category OR with the same tag. It’s a logic “OR”.
    How to get all products of the same category AND with the same tags? (AND logic)?

    1. You mean this:

      if ( has_term( 'tables', 'product_cat' ) && has_term( 'red', 'product_tag' ) ) { } 
  3. Anyway to use the product shortcode to display products by the same taxonomy term as the single product on the single product page?

    1. Hey Robert, 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!

  4. Thanks, Rodolfo! I’m using one right now. Just FYI, you have copy and paste error on this one. you have “tables” in the add action and “rock” in the function:)

    add_action( 'woocommerce_before_single_product', 'bbloomer_print_banner_if_product_belongs_to_category_tables' );
     
    function bbloomer_print_banner_if_product_belongs_to_category_rock() {
       if ( has_term( 'tables', 'product_cat' ) ) {
          echo '';
       }
    }
    
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 *