Treehouse: Grow your CSS skills. Land your dream job.

Count posts excluding certain categories

  • # February 10, 2011 at 11:23 am

    I’ve been searching for the right way to count all published posts but excluding specific categories. I know of the function wp_count_posts but it doesn’t have the option to exclude specific categories. So I came up with the following:

    < ?php
    $categories = get_categories('exclude=1,2,3');
    foreach($categories as $category) {
    $total += $category->count;
    echo $total;

    It works! But is that the correct way or is there some other way I’m missing?

    # February 10, 2011 at 11:36 am

    You could also use get_posts() with the category__not_in parameter and then counting the number of returned posts but I’m not sure if it would be a faster/more efficient solution.

    # February 15, 2011 at 10:31 am

    This loop was accepted at WP-Snippets so I guess it’s a good way of doing it!

    # February 15, 2011 at 3:32 pm

    Well done! It’s short and looks clean enough.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.