开发者

Wordpress Exclude Categories Posts but retain Post Count per page

开发者 https://www.devze.com 2023-04-01 20:06 出处:网络
So I am excluding posts is several categories from a blog page (categories 4-11). I am doing so using the following code:

So I am excluding posts is several categories from a blog page (categories 4-11).

I am doing so using the following code:

if (have_posts()) : while (have_posts())  : the_post(); 
    $category = get_the_category();


   开发者_运维百科  if($category[0]->cat_ID > 11 || $category[0]->cat_ID < 4){
        continue;
     }

This works to exclude the categories posts from the page but it does not retain the post count per page being 10 or whatever it is set to in the Admin.

How would I programatically decrement the post count by one for posts I skip in the Wordpress Loop so I exclude the category posts i do not want but also retain the same amount of posts per page?


The easiest (but not most efficient) way to do this is to replace the global $wp_query by a custom query using category__in...

global $wp_query;
$wp_query = new WP_Query(array("category__in"=>array(4,5,6,7,8,9,10,11)));

...then do the loop...

while (have_posts()){
     the_post();

     //etc..
}

This will make the paging accurate, and you can rely on the high-level templating functions like next_posts_link().

Probably a more efficient way (that doesn't throw out and replace $wp_query) would be to mess with the original query before it's executed...

 add_action('parse_query', 'my_parse_query');
 function my_parse_query(&$q){
      //decide if you want to mess with the query....
      //if not, return
      $q->set_query_var("category__in", array(4,5,6,7,8,9,10,11));
 }

my_parse_query would be called on every query, including those for pages and single posts, so you would have to add some logic to the function to only add category__in where it made sense.

0

精彩评论

暂无评论...
验证码 换一张
取 消