Recently I had to add the count of posts in each category or archive on the sidebar. I knew exactly what I have to do, search wp_list_categories
in the WordPress Code Reference. I copied the code and modified it to look the way I want just to realize that the count number is not inside the link.
Looking online on how to do this, I found what I was searching for on GitHub. You can add the code in functions.php
and the post count will be placed inside the link.
/* This code filters the Categories archive widget to include the post count inside the link */
add_filter('wp_list_categories', 'cat_count_span');
function cat_count_span($links) {
$links = str_replace(' (', ' (', $links);
$links = str_replace(')', ')', $links);
return $links;
}
/* This code filters the Archive widget to include the post count inside the link */
add_filter('get_archives_link', 'archive_count_span');
function archive_count_span($links) {
$links = str_replace(' (', ' (', $links);
$links = str_replace(')', ')', $links);
return $links;
}