list

Display A List of Custom Taxonomy Terms with Posts Number

A WordPress taxonomy is a way to organize groups of posts and custom post types. By default, WordPress comes with two taxonomies called categories and tags. However, if you are using a custom post type, then you may need custom taxonomies.

There are two types of custom taxonomies.

  1. Hierarchical Taxonomy (works like categories)
  2. Non-Hierarchical Taxonomy (works like tags)

For instance, you can create a custom post type called ‘Quotes’ and sort it using custom taxonomies ‘Topics’ and ‘Writers’. Each topic and each writer is a term.

What if you want to display a list of topics or a list of writers with their posts number?

WordPress has pre-made categories and tag cloud widget. But there is no widget to show custom taxonomy terms list.

categories

Categories widget’s output will be something like this:

Category Widget

How can we achieve similar result for custom taxonomies?

Add following code to the template where you want to show the list:

$custom_cats = get_terms('quote-writer', array('hide_empty' => true));
echo '<ul>';
foreach ( $custom_cats as $term ) {
    $term_link = get_term_link( $term);
    echo '<li><a href="'.$term_link.'">'.$term->name . ' (' . $term->count . ')</a></li>';
}
echo '</ul>';

Change ‘quote-writer‘ to your custom taxonomy name. This works for both hierarchical and non-hierarchical taxonomy.

Let me know if this works for you or not.

Spread the love

A teacher by profession, a traveler by passion and a netizen by choice.

Morshed Alam

You use WordPress! Why don't we share our experience! It may be a tutorial, tips, tricks or about security, performance or WordPress news. Write Today

Leave a Comment

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