Display deepest child category for current product in woocommerce

This seems like it should be easy to do but I haven’t been able to, and cannot find any posts regarding it.

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

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

If this example is the product’s ancestry, 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 lowest child, be the product on the archive page, or single product page.

Any idea of how this can / should be done?

Related posts

Leave a Reply

2 comments

  1. 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;
          }
        endforeach;
    
    endif;
    
  2. I finally found the anwser at https://wordpress.stackexchange.com/a/55921/59863 I added the proper taxonomy for woocommerce, and a foreach / echo at the bottom to spit out the name.

    //Get all terms associated with post in woocommerce's 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 downside to this code is that if a product only has 1 category with a parent value of 0 it will break. I don’t need this functionality at the moment, but I am going to come back and fix this with a “if null do this instead”.