Display deepest child category for current product in woocommerce

11,673

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;
Share:
11,673
Aaron T
Author by

Aaron T

Updated on June 04, 2022

Comments

  • Aaron T
    Aaron T almost 2 years

    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?

    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?

  • Aaron T
    Aaron T over 9 years
    Hmmm, also wouldn't a parent value of 0 indicate a top level category not a bottom level one?
  • manishie
    manishie over 9 years
    It's not the parent value being 0. the code says take the current term_id and make it the parent. then use the get_categories function to return the children of that parent (the current term). then if there are no posts returned, that means it's NOT a parent, so therefore it's the one you're looking for.
  • Aaron T
    Aaron T over 9 years
    Ah nice! downside though, i think get_the_category() doesn't work with woo, because it stores it's categories in a custom taxonomy, not the offical wp category spot. $categories was empty after I tried to use it.
  • manishie
    manishie over 9 years
    updated my answer to the woocommerce product_cat taxonomy (changed 2 lines).
  • c0dehunter
    c0dehunter about 6 years
    Where do you have to put this?
  • Tuhin A.
    Tuhin A. over 2 years
    the deepest category of the product may have children too and those children categories may not be assigned to the product. In that case, deepest category identification based on children count is not valid.