1

I have the following product structure:

-- Category

-- Deep

-- Deeper

Currently the last child category "deeper" will only be used for labeling products. What I want to do is to echo only the last child category "Deeper".

Any idea how to do that?

Thanks!

EDIT: Solution found on Stackoverflow. LINK.

// 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;
3
  • There is no concrete existing answers on this issue. I found an interesting approach though by @TomJNowell here that can be a good starting point. I would like to tackle this, but I'll only have time to code and experiment with this in the new week. I hope you find your answer sooner than that. :-) – Pieter Goosen Apr 24 '15 at 5:55
  • Found a solution on stackflow stackoverflow.com/questions/25896981/… – HunterListInsight Apr 24 '15 at 11:51
  • Great. I did't know that you actually wantes this on a per product base :-). You should post that solution (your edit to your question) as an answer and accept your own answer – Pieter Goosen Apr 24 '15 at 12:09

Your Answer

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

Browse other questions tagged or ask your own question.