If you have tried using the in_category()
function to check if a specific product belongs to a certain product category, you probably did not succeed. In this guide, we will see why…
This is a common mistake indeed. So let’s start by noting that products in WooCommerce are a custom content type called product
, and the product categories themselves are a taxonomy called product_cat
. Are we working with functions for categories and tags for taxonomies? Of course not…
Unlike the is_product_category()
function, in the case of checking if a product belongs to a specific category, WooCommerce does not provide conditional tags, so we must use WordPress’s default conditions:
has_term( $terms, 'product_cat', $post );
- (string|integer|array)
$terms
– Used to pass the category name, category ID, or an array of IDs. - The second parameter is the name of the taxonomy, which in this case for product categories is
product_cat
. Alternatively, for product tags, we would useproduct_tag
. - (integer|object)
$post
– The product’s ID or a WP_Post object. If not supplied, it will default to the current product in the loop.
Code Examples
Now let’s look at a few code examples:
if( has_term( 4, 'product_cat' ) ) {
// do something if the current product in the loop is in product category with ID 4
}
if( has_term( array( 'sneakers', 'backpacks' ), 'product_cat', 50 ) ) {
// do something if the product with ID 50 is either in the 'sneakers' or 'backpacks' category
} else {
// do something else if it isn't
}
if( has_term( 5, 'product_tag', 971 ) ) {
// do something if the product with ID = 971 has a tag with ID = 5
}
That’s it for this short post, and thanks to Misha for the knowledge appearing in this post. Check his website!