How To Check If A Woocommerce Product Has A Category

Today, while working on a client Woocommerce website dedicated to pickup / takeout only, I wanted to use a category to designate which store locations a product is available.

I get that using categories isn’t always the best way to do it, but the Coronavirus epidemic is making this more of a rush project…and this works just fine.

So, once I had all the products categorized, I wanted to be able to show certain text on the front of the site to let them know which locations had it in stock. This meant that I would need to know if a product had the category for each location.

Check If A Woocommerce Product Has A Category

You do this by creating an If statement that checks the post terms for the name of the category. You’d want to do this to create logic for many different uses. I used it to show some special text on the front of the site, but you could use it to do many many things based on the category it has.

Here’s the code:

if(has_term( 'CATEGORY NAME HERE', 'product_cat', $product->post )){
  //do something
}

You must use “has_term” because a Woocommerce product is a custom post type and with a custom taxonomy and you can only access those with that function.

If you want to check if a page has a category, use this code:

if(has_category('CATEGORY NAME HERE')){
  //do something
}

Leave a Reply

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