On a WordPress page we are counting and displaying the amount of posts for all categories. Meaning, all sub category posts should be counted as posts for the main category.
Let’s say, the name of the main category is "E" and the sub categories are "A", "B", "X" and "Z".
My function seems to be wrong. It’s counting the posts from "X" and "Z" to category "E", but it’s not counting the posts from "A" and "B".
What can be the reason for this? Is it code related or can there be another mistake? I have double checked that slugs are unique and that the hierarchy from main and sub categories is correct.
This is my current code:
$categories = get_categories([
'hide_empty' => 0,
'parent' => 0,
]);
foreach ($categories as $category) {
$subcategories = get_categories([
'hide_empty' => 0,
'parent' => $category->term_id,
]);
$total_count = $category->count; // Initialize with the main category count
foreach ($subcategories as $subcategory) {
$total_count += $subcategory->count; // Add subcategory counts
}
echo '<input type="checkbox" data-select="sectionFilter" id="section_' . $category->term_id . '" value="' . $category->term_id . '">';
echo '<label for="section_' . $category->term_id . '">';
}
PS: I don’t have that much experience with WP / PHP coding, so please excuse if this is a stupid question.
UPDATE: The function is working perfect. As soon as I rename the child categories A and B to a name that starts with a character later that E (let’s say T). The count is correct then. If I rename X to C, it is also not being counted to the main categoriy.
Even the order in the WP Posts dashboard is weird. It displays "E, X", but "A, E" for the categories in question. As if it is tagging A as a main category and E as a child.
Summary: The correct count seems to be depending on the name of the child categories. How can this be fixed?
2
Answers
You can add this code to your theme’s
functions.php
file:Then, you can add this shortcode to your posts, pages, and widgets using the following code:
[shortcode_category_post_counts]
It will run the function and show the output. Like: