Getting the lowest level category (or custom taxonomy) for a WordPress post

Working on a client project which applies a hierarchical custom taxonomy to a custom post type I needed to find the lowest level set for the post. Assuming that there is only one hierarchy applied to the post the following does the trick, for categories (running on the single post page):

$categories = get_categories();
$parents = array();
if($categories){
	foreach ($categories as $category){
		$ids[] = $category->term_id;//read the category ids into an array
		if ($category->parent) $parents[] = $category->parent;//read the parent ids into an array
	}
}		
$low_categories =  array_diff ($ids,$parents);//get the ids which are not parents
$lowest_category = array_shift($low_categories);//read the first id (just in case there's more than one)

If you’re working with a custom taxonomy called, say, ‘classification’ then this becomes:

$post_classifications = get_the_terms($get_the_ID,'classification');
if($post_classifications){
	foreach ($post_classifications as $post_classification){
		$ids[] = $post_classification->term_id;
		if ($post_classification->parent) $parents[] = $post_classification->parent;
	}
}		
$low_class =  array_diff ($ids,$parents);
$classification = array_shift($low_class);

Hope this helps someone else…

Tags:

One response to “Getting the lowest level category (or custom taxonomy) for a WordPress post”

  1. Joe says:

    Wow, this was EXACTLY what I needed thank you so much you’re a genius.

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.