The question:
I do have a custom taxonomy called “countries”. How do I get each term (country) with the number of its published posts in brackets, like the following:
- Uruguay (3)
- Chile (5)
- Thailand (2)
- etc.
With following code the number of all terms in the “countries” taxonomy is displayed:
$countries_count = wp_count_terms( 'countries' );
echo $countries_count;
But I just know that this is just a starting point of my problem. Any suggestions?
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
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 . ' (' . $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 ) . '" rel="nofollow noreferrer noopener">' . $term->name . ' (' . $term->count . ')' . '</a></li>';
}
echo '</ul>';
}
?>
Method 2
You can try it with WP Query. I haven’t tested it yet, so please let me know if it works.
$query = new WP_Query( array( 'taxonomy' => 'term', 'posts_per_page' => -1 ) );
$count = $query->post_count;
Method 3
I can’t test this right now but try getting all the terms for “countries” and then loop through them and get the wp_count_terms for each of them.
$terms = get_terms("countries");
if ( !empty( $terms ) && !is_wp_error( $terms ) ){
echo "<ul>";
foreach ( $terms as $term ) {
$args = array( 'slug' => $term->slug, );
echo "<li>" . $term->name . "(" . wp_count_terms('countries', $args) . ")</li>";
}
echo "</ul>"; }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0