WordPress

Add Category Post Counts to the WordPress Menu

Struggling with a way to add category post counts your WordPress menu?

Add the following code to your functions.php file.

add_filter('the_title', 'generate_category_post_count_title', 10, 2);
function generate_category_post_count_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;
}

You can see the code working live on this website. Check it out by selecting the down arrow on my main menu to the left.

Hello, I'm a project manager, previous business owner, web developer, home-owner, parent, and a Cleveland sports fan.

Published by

Corey Schario

Hello, I'm a project manager, previous business owner, web developer, home-owner, parent, and a Cleveland sports fan.

Leave a Reply

Your email address will not be published. Required fields are marked *