'Is there any ways to count posts in categories?
I have nearly 500 categories in my web site. I want to add a function to count posts in each category. Since the categories are too many, i can't try to add posts id or name to each category code. I need wordpress to do it automatically for each category. Is there any way you can show me to do that?
{
<a href="<?php echo $collection_link; ?>">
<h5 class="text-center card-title">
<?php the_category(); ?>
</h5>
</a>
<a href="<?php echo $collection_link; ?>">
<p class="text-center d-flex justify-content-center card-text">
<?php //this is where post count should be displayed ?>
</p>
</a>
</div><!-- end card-body -->}
Solution 1:[1]
function count_cat_post($category) {
if(is_string($category)) {
$catID = get_cat_ID($category);
}
elseif(is_numeric($category)) {
$catID = $category;
} else {
return 0;
}
$cat = get_category($catID);
return $cat->count;
}
// Usage
echo count_cat_post('1');
echo count_cat_post('General');
Taken from here. A simple google search would have gave your answer!
If you're using the the_category() function, you will need to filter a post count in to that function. This answer on a post over at WordPress Stack Exchange explains how to do that. Please note that the_category() function is actually just echo get_the_categories(); so the filter in the linked answer should work for you.
For completeness, here's the code from the answer linked above.
add_filter('get_the_categories', 'wpse50876_the_counter');
function wpse50876_the_counter($cats){
foreach($cats as $cat){
$cat->cat_name = $cat->cat_name.'('.$cat->count.')';
}
return $cats;
}
Solution 2:[2]
inside category.php that would be
$category = get_queried_object();
$count = $category->category_count;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Hebe |
