WordPress – Print Single Post Taxonomy Terms in Hierarchical Order

wordpress-Taxonomy-Hierarchical

In this WordPress tutorial we will learn how to print single post taxonomy terms in hierarchical order. This taxonomy can be default WoordPress post category or custom taxonomy.

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

And we want to print / display these categories on single post page in same hierarchical order, like:

Parent, child, sub-child

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

1
2
3
4
5
6
7
8
<?php
$taxonomy = 'category'; // change this to your custom taxonomy name.
$terms = wp_get_post_terms( $post->ID, $taxonomy, array( "fields" => "ids" ) );
if( $terms ) {
  $terms = trim( implode( ',', (array) $terms ), ' ,' );
  wp_list_categories( 'title_li=&taxonomy=' . $taxonomy . '&include=' . $terms . '&separator=, &style=' );
}
?>

In above code, on line 2, change the value of $taxonomy to your custom taxonomy name if you wish to use this code for custom taxonomy terms.

Display customisation

Please refer to WordPress function wp_list_categories to customise the display of taxonomy terms.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *