This can be achieved many ways. But, the below method is most prominent to me.
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;
}
Note:
$category->count
doesn’t always contain the proper value of
posts. In case any other CPT is usingcategory
as taxonomy, the
count would be combination of posts and CPTs.Usage: The code should go on your child theme’s
functions.php
file
(if exists), or the parent theme’sfunctions.php
file or either in a
plugin.