How to display the number of posts in a category in WordPress navigation menu

You may want to display the number of posts in a category in WordPress menu. For example, it's possible to show category post count in main navigation menu as shown:

How to display the number of posts in a category in WordPress main navigation menu

To display category post count in main navigation menu, please add the following code to your theme function file:

add_filter('the_title', 'wpse165333_the_title', 10, 2);
function wpse165333_the_title($title, $post_ID)
{
if( 'nav_menu_item' == get_post_type($post_ID) )
{
if( 'taxonomy' == get_post_meta($post_ID, '_menu_item_type', true) && 'category' == get_post_meta($post_ID, '_menu_item_object', true) )
{
$category = get_category( get_post_meta($post_ID, '_menu_item_object_id', true) );
$title .= sprintf(' (%d)', $category->count);
}
}
return $title;
}

It's recommended to install a child theme before you add the above code. It's simple to create a child theme with the Child Theme Configurator plugin.


3s