Nov
13
How to Display Your WordPress Category Counts
- Filed under: Tutorials
In this tutorial we will show you how to display the number of posts you have made that are associated to each category you have designated.
First, located where you have your categories displayed on your site, by default, it is in the sidebar.php file.
Once you have the file opened, locate the function that populates your categories, it is named wp_list_cats();. This function generates a list of all of your categories that you have associated to each of your posts, if you have not assigned a category to any of your posts, then they all be be placed in the default category: Uncategorized.
A typical category list will looking something like this:
-------------------
| categroy link 1 |
-------------------
| category link 2 |
-------------------
| category link 3 |
-------------------
But, you want your readers to know how many posts you have in each of your categories. Most of the default WordPress functions have the ability to customize it’s query, and the wp_list_cats(); function is no different. In the function, add the string ‘count=1′ to designate that you would like the function to also return a count. So your new category function would look like this: wp_list_cats('count=1');.
Easy enough? Well, Houston, we have a problem. The built-in class that creates the category list adds the count outside of the anchor tag, creating a list that looks very unappealing.
-------------------
| categroy link 1 |
-------------------
(15)
-------------------
| category link 2 |
-------------------
(8)
-------------------
| category link 3 |
-------------------
(25)
In order to achieve a more desirable and more semantic approach, you will need to edit the classes.php file that is located in the wp-includes directory.
Find line 596 in the file:
$link .= $cat_name . '';
Change that to:
//$link .= $cat_name . '';
$link .= $cat_name;
if ( isset($show_count) && $show_count ) {
$link .= ' (' . intval($category->count) . ')';
}
Then go down a few lines and fine the code and comment it out or remove it:
if ( isset($show_count) && $show_count )
$link .= '(' . intval($category->count) . ')';
Now, when you view your category list, it should appear something like this:
------------------------
| categroy link 1 (15) |
------------------------
| category link 2 (8) |
------------------------
| category link 3 (25) |
------------------------
