1

I'm currently using the following code to try and display the child category of products:-

global $post, $product;
$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
?>

<h1 itemprop="name" class="product_title entry-title"><?php the_title(); ?></h1>
<h3 itemprop="name" class="product_title entry-title">by <?php echo $product->get_categories(); ?></h3>

This outputs both the parent and child category separated by a comma. Is there an easy way to just display the child category and not the parent category?

Any help or pointers are much appreciated ;)

3

I was directed to this post – which solved my problem 100%. Here is the solution I used from that post.

// get all product cats for the current post
$categories = get_the_terms( get_the_ID(), 'product_cat' ); 

// wrapper to hide any errors from top level categories or products without category
if ( $categories && ! is_wp_error( $category ) ) : 

    // loop through each cat
    foreach($categories as $category) :
      // get the children (if any) of the current cat
      $children = get_categories( array ('taxonomy' => 'product_cat', 'parent' => $category->term_id ));

      if ( count($children) == 0 ) {
          // if no children, then echo the category name.
          echo $category->name;
      }
    endforeach;

endif;
  • Please add a solution and not just a link to where someone might find a solution. Link only answers is poor quality answers which should be avoided – Pieter Goosen Aug 25 '15 at 8:42
  • Hi @PieterGoosen, sorry, relatively new at posting here. I have now updated my post to have the solution as well as the link. – Craig Paterson Aug 25 '15 at 11:55
  • Great, thank you. Now, even when the link dies, your answer will still be useful to others as well. +1 – Pieter Goosen Aug 25 '15 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.