How to exclude posts from category posts count

I have a custom loop to display posts based on a custom field. My problem is that if i have 2 posts and exclude 1 from the loop the category posts count (categories list widget with show count enable) still remains 2.

Topic exclude count categories Wordpress

Category Web


Assuming you have a list containing the post IDs you want to exclude, you could start with something like (PHP 7.3):

function exclude_posts_from_category( array $cat_args ): array {
    $exclude = array(); // TODO Add post IDs to exclude.
    $cat_args['exclude'] = $exclude;
    return $cat_args;
}
add_filter( 'widget_categories_args', 'exclude_posts_from_category', 10, 1 );

You can read about the widget_categories_args filter here. Additionally, you can alter the $cat_args array using a combination of arguments that can be found in the documentation of the wp_list_categories() function.

I did not fully test this code, so let me know in case you're having any trouble.


If you want to exclude posts from all queries, if you are not an "admin", and excluding the "single" query - so you can open the post, you can use this:

add_action('pre_get_posts', 'exclude_posts_from_all_queries');
function exclude_posts_from_all_queries($query) {
  $exclude_posts = array('9');
  if ( !is_admin() && !is_single() ) {
    $query->set('post__not_in', $exclude_posts);
  }
}

Just add the Posts ID number to $exclude_posts array.

Hope that it helps,
Cheers

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.