Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Count posts excluding certain categories

  • This topic is empty.
Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #31570
    jacorre
    Participant

    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:

    
    $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?

    #61372
    Keyamoon
    Member

    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.

    #60224
    jacorre
    Participant

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

    #60174
    TheDoc
    Member

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

    #194719
    poorpaddy
    Participant

    Is there way to do this for a specific post type? Here’s what I am working with and trying to exclude categories,

    <?php
    $count_posts = wp_count_posts('sponsors');
    $published_posts = $count_posts->publish;
    $count = $published_posts/7;
    $args = array(
    'posts_per_page' => -1,
    'post_type' => 'sponsors'
    );
    query_posts($args);
    ?>

    #194727
    Paulie_D
    Member

    Serious necro-post, dude!

    I hope someone can help you.

    #194730
    poorpaddy
    Participant

    I figured it out. Just needed to add 'cat' => '-71,-72,-73' to the $args.

    <?php
    $count_posts = wp_count_posts('sponsors');
    $published_posts = $count_posts->publish;
    $count = $published_posts/7;
    $args = array(
    'posts_per_page' => -1,
    'post_type' => 'sponsors',
    'cat' => '-71,-72,-73'
    );
    query_posts($args);
    ?>

Viewing 7 posts - 1 through 7 (of 7 total)
  • The forum ‘Back End’ is closed to new topics and replies.