Adding Post Counts to Menu (Nav) Programmatically?

WordPress’ get_categories() function returns an array of category objects, each of which has a “count” property for the number of posts in that category. So something like this would get you a list of links to category pages:

$categories = get_categories();

$markup = '<ul>';
foreach( $categories as $category ) {
   $catName = $category->category_nicename;
   $count   = $category->count;
   $url     = get_category_link( $category->cat_ID );

   $markup .= '<li>';
     $markup .= "<a href=\"{$url}\">{$catName} ({$count})</a>";
   $markup .= '</li>';
}
$markup .= '</ul>';

That would allow you to show a count using a single query. I’m sure there is a way to find a count of “new” posts using a more complex custom query instead of get_categories(), but I’d probably just eat any extra overhead of making another query for each category as opposed to trying to do it all in a single query. Call me lazy.

Leave a Comment