Skip to main content

WordPress – Print Single Post Taxonomy Terms in Hierarchical Order

Submitted by admin on Thu, 12/16/2021 - 10:28

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:
- 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.

$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.


Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.