Display deepest child category for current product in woocommerce

It seems like it should be easy to do, but I have not been able and cannot find any posts about it.

I can display all categories related to a product or top category, but how do you echo only the lowest / deepest category for a product?

Cat-A [x]
  Cat-B [x]
    Cat-C [x]
  Cat-D [ ]
Cat-E [ ]
  Cat-F [ ]
    Cat-G [ ]
      Cat-H [ ]


If this example is a product pedigree, all I want to print is "Cat-C".

But I don't want to manually set the category level like other solutions, I want it to always print the junior child, is a product on an archive page or a separate product page.

Any idea on how / should this be done?


source to share

2 answers

Try something like:

// 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;





I finally found anwser at https://wordpress.stackexchange.com/a/55921/59863 I added the correct taxonomy for woocommerce and foreach / echo at the bottom to spit out the name.

//Get all terms associated with post in woocommerce taxonomy 'product_cat'
$terms = get_the_terms( $post->ID, 'product_cat' );

//Get an array of their IDs
$term_ids = wp_list_pluck($terms,'term_id');

//Get array of parents - 0 is not a parent
$parents = array_filter(wp_list_pluck($terms,'parent'));

//Get array of IDs of terms which are not parents.
$term_ids_not_parents = array_diff($term_ids,  $parents);

//Get corresponding term objects.
$terms_not_parents = array_intersect_key($terms,  $term_ids_not_parents);

//Extract the name of the category from the array and post it.
foreach($terms_not_parents as $term_not_parent)
echo $term_not_parent->name;


The only drawback of this code is that if a product has only 1 category with a parent value of 0, it will break. I don't need this functionality at the moment, but I'm going to go back and fix it with "if null".



All Articles