admin管理员组

文章数量:1313361

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.

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.

Share Improve this question asked Sep 30, 2014 at 7:55 ChristopherChristopher 3353 silver badges14 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

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

本文标签: categoriesHow to exclude posts from category posts count