wordpress-Taxonomy-Reverse-Hierarchical

In this WordPress tutorial we will learn how to print / display terms of a custom taxonomy or WordPress default category in hierarchical order and reverse hierarchical order in single post.

Let’s say we have a post with following hierarchical custom categories:
Parent
– child
— sub-child

WordPress Default Display

By default, WordPress will print these taxonomy terms in alphabetical order.
But we want to display these terms in hierarchical order and reverse hierarchical order.

Display Terms in Hierarchical Order

To display terms of a custom taxonomy or terms of WordPress default category in hierarchical order in single post like below:

Parent, child, sub-child

Use below code in single.php where you want to print the taxonomy terms.


<?php
/*
 * Print Taxonomy Terms in Hierarchical Order
 */
$taxonomy = 'YOUR_TAXONOMY_NAME'; // change this to your custom taxonomy name.
$taxonomy_terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $taxonomy_terms ) {
	$term_array = trim( implode( ',', (array) $taxonomy_terms ), ' ,' );
	$neworderterms = get_terms($taxonomy, 'orderby=none&include=' . $term_array );
	foreach( $neworderterms as $orderterm ) {
		echo '' . $orderterm->name . ', ';
	}
}
?>

Note: Change YOUR_TAXONOMY_NAME to your taxonomy name.

Print Taxonomy Terms in Reverse Hierarchical Order

If you requirement is to print taxonomy terms in reverse hierarchical order like:

Sub-child, Child, Parent

Then use below code in single.php file.


<?php
/*
 * Print Taxonomy Terms in Reverse Hierarchical Order
 */
$taxonomy = 'YOUR_TAXONOMY_NAME'; // change this to your custom taxonomy name.
$taxonomy_terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $taxonomy_terms ) {
	$term_array = trim( implode( ',', (array) $taxonomy_terms ), ' ,' );
	$neworderterms = get_terms($taxonomy, 'orderby=none&include=' . $term_array );
	foreach( array_reverse($neworderterms) as $orderterm ) {
		echo '' . $orderterm->name . ', ';
	}
}
?>

Note: Change YOUR_TAXONOMY_NAME to your taxonomy name.

In above code, on line 5, change YOUR_TAXONOMY_NAME to your custom taxonomy name. Change this to category to display terms of wordpress default category.
Tags