WordPress: Taxonomy hierarchy on a single post

Taxonomy hierarchy on a single post

Cambodia Web Design WordPress Tips & Tricks

WP Taxonomy hierarchy parent children

In WordPress, you can easily get the custom taxonomy terms that belong to the current post. Just use get_the_term_list. That gives you links to all taxonomy terms of that particular post.
However, they’re not hierarchical, so if you have a parent category, that will be just displayed within the list (in alphabetical order). Probably not how you want it.

How to get your single post taxonomies in a hierarchical order in WordPress? You have to use wp_get_post_terms().

Even then, it’s not so obvious how to get your current post’s terms in hierarchical order, including links to the term. But it is possible, see the code below.


function taxonomy_hierarchy() {
	global $post;
	$taxonomy = 'your_taxonomy'; //Put your custom taxonomy term here
	$terms = wp_get_post_terms( $post->ID, $taxonomy );
	foreach ( $terms as $term )
        {
	if ($term->parent == 0) // this gets the parent of the current post taxonomy
	{$myparent = $term;}
        }
	echo ''.$myparent->name.'';
	// Right, the parent is set, now let's get the children
	foreach ( $terms as $term ) {
		if ($term->parent != 0) // this ignores the parent of the current post taxonomy
		{ 
		$child_term = $term; // this gets the children of the current post taxonomy
		echo ''.$child_term->name.'';
		}
    }	
}

Put this code in your theme’s (preferably a child theme’s) ‘functions.php’ file and call it within a theme template or hook it into an action. To explain how to do that is beyond the scope of this WordPress tip, sorry.

Of course you can add other details in the HTML and style the output in CSS. In the example image, I’ve divided the output in a ‘Main Category'(the parent) and ‘Business Type'(the children).

Just to be clear: this is about getting hierarchical taxonomy terms in use by the current post.
Getting all taxonomy terms (independent of what terms are in use by the current post) in hierarchical order is quite easy,
just use _get_term_hierarchy.