Name of last category level for a post

Try the following. I’ve used get_the_terms so it is readily extendible to any taxonomy.

This will return an array of terms (event if it contains just one). For instance, the post may have terms a,b,c,d,e in the relationship:

a   >   b  >   c      (parent > child)
d   >   e

In which case the following will return (as an array) the terms c and e. Whereas with the structure

a   >   b  >    c  >  d   >   e      (parent > child)

It will return an array of one term – e.

//Get all terms associated with post in taxonomy 'category'
$terms = get_the_terms(get_the_ID(),'category');

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

Leave a Comment