How to check if the product is in a certain category on a single-product.php in Woocommerce?

I don’t think get_categories() is the best option for you in this case because it returns a string with all the categories listed as anchor tags, fine for displaying, but not great for figuring out in code what the categories are. Ok, so the first thing you need to do is grab the product/post object for the current page if you don’t already have it:

global $post;

Then you can get the product category term objects (the categories) for the product. Here I’m turning the category term objects into a simple array named $categories so it’s easier to see what slugs are assigned. Note that this will return all categories assigned to the product, not just the one of the current page, ie if we’re on /shop/audio/funzo/:

$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;

Then we just have to check whether a category is in the list:

if ( in_array( 'audio', $categories ) ) {  // do something

Putting it all together:

<?php
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;

if ( in_array( 'audio', $categories ) ) {
  echo 'In audio';
  woocommerce_get_template_part( 'content', 'single-product' );
} elseif ( in_array( 'elektro', $categories ) ) {
  echo 'In elektro';
  woocommerce_get_template_part( 'content', 'single-product' );
} else {
  echo 'some blabla';
}

Hopefully this is what you were looking for and answers your question.

Leave a Comment