• why this function is working

    function custom_add_count_on_archive_title( $title ) {
        $term = get_queried_object();
        if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
            $title .= ' <span>'.$term->count.'</span>';
        }
    
        return $title;
    }
    add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );

    and this other, derivated from the above one, not

    function custom_add_count_on_archive_title( $title ) {
        $term = get_queried_object();
        $term_id = get_queried_object()->term_id;
        if( $term instanceof WP_Term && 'category' === $term->taxonomy ) {
            
            $children_terms = get_terms(array(
                'taxonomy' => 'category',
                'child_of' => $term_id,
            ));
            
            $total_count = 0;
            
            if (!empty($children_terms) && !is_wp_error($children_terms)) {
                foreach ($children_terms as $child_term) {
                    $total_count += $child_term->count;
                }
            }
        
            $title .= ' <span>'.$total_count.'</span>';
        }
        return $title;
    }
    add_filter( 'get_the_archive_title', 'custom_add_count_on_archive_title', 10, 1 );

    The page I need help with: [log in to see the link]

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Seems to work for me if you want only the total post count of child terms. If you want to include the parent term count as well, the $total_count = 0; line should instead be $total_count = $term->count;

    If your code is still not working for you, in what way exactly is it not working? I’m not sure what you are expecting.

    BTW, the second line could just be $term_id = $term->term_id;. No point in calling a function twice when once will do 🙂 Getting the queried object doesn’t involve much overhead, so in this case it makes little difference. In other cases it could make a difference. If you wanted to, you could even simply use $term->term_id everywhere you now have $term_id and do away with the second line all together. This would be more of a coding style choice than any performance gain, though avoiding an assignment does save a small amount of memory. Not enough to be concerned about.

    Thread Starter sacconi

    (@sacconi)

    I applied the changes you suggested and now it works!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Adding count also to parent categories’ is closed to new replies.