Display the number of published posts for each custom taxonomy term?

You can use get_terms to get the list of all terms associated with a taxonomy. Once you have all the separate terms, you can use $term->name to display the name of the term and $term->count to retrieve the amount of posts inside that specific term.

Here is a slightly modified version of the code found in the codex. You can futher modify the output as you need

<?php  
$terms = get_terms('countries');

 if ( !empty( $terms ) && !is_wp_error( $terms ) ){
     echo '<ul>';
     foreach ( $terms as $term ) {
       echo '<li>' . $term->name . '&nbsp;(' . $term->count . ')' . '</li>';
     }
     echo '</ul>';
 } 
?> 

EDIT

Thanks to @Traveler, here is another version of my code if you need the links to be clickable.

<?php 

  $terms = get_terms('countries'); 
  if ( !empty( $terms ) && !is_wp_error( $terms ) ){ 
  echo '<ul>'; 

  foreach ( $terms as $term ) { 
     $term = sanitize_term( $term, 'countries' ); 
     $term_link = get_term_link( $term, 'countries' ); 

      echo '<li><a href="' . esc_url( $term_link ) . '">' . $term->name . '&nbsp;(' . $term->count . ')' . '</a></li>'; 
  } 
  echo '</ul>';
  }

?> 

Leave a Comment