skip to Main Content

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


  1. The correct way of getting the total number of posts is:
    
    <?php $count = $custom_posts->found_posts; ?>
    
    For category --
        <?php
        $args = array( 
            'category' => 1, 
            'post_status' => 'publish', 
        ); 
        $query = new WP_Query( $args ); 
        $count = $query->found_posts; 
         
        echo $count; ?>
    
    Login or Signup to reply.
  2. You can add this code to your theme’s functions.php file:

    <?php
    // functions.php
    function display_category_post_counts_atakanau() {
        $categories = get_categories();
        
        $category_list = array();
        
        foreach ($categories as $category) {
            if ($category->category_parent == 0) {
                $category_list[$category->name] = array(
                    'total_post_count' => $category->count,
                    'sub_categories' => array()
                );
            } else {
                $parent = get_category($category->category_parent);
                while ($parent->category_parent != 0) {
                    $parent = get_category($parent->category_parent);
                }
                if (!isset($category_list[$parent->name])) {
                    $category_list[$parent->name] = array(
                        'total_post_count' => $parent->count,
                        'sub_categories' => array()
                    );
                }
                $category_list[$parent->name]['sub_categories'][$category->name] = $category->count;
                $category_list[$parent->name]['total_post_count'] += $category->count;
            }
        }
        
        $show_level_2 = false;
        $output = '<ul>';
        foreach ($category_list as $category_name => $info) {
            $output .= '<li>' . $category_name . ' - Total Post Count: ' . $info['total_post_count'];
            
            if ($show_level_2 && !empty($info['sub_categories'])) {
                $output .= '<ul>';
                foreach ($info['sub_categories'] as $sub_category_name => $post_count) {
                    $output .= '<li>' . $sub_category_name . ' - Post Count: ' . $post_count . '</li>';
                }
                $output .= '</ul>';
            }
            
            $output .= '</li>';
        }
        $output .= '</ul>';
        
        return $output;
    }
    add_shortcode('shortcode_category_post_counts', 'display_category_post_counts_atakanau');
    

    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:
    sample html output

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search