如何从wordpress中的category.php查询中按ID排除帖子

How to exclude a post by id from the category.php query in wordpress

我有一个模板,其中有一个主要的最新精选帖子(标记为精选),然后在其下方再添加8个。
在主页上,我能够查询最新的特色文章,然后将其ID传递给pre_get_posts wordpress过滤器中的函数。 它在那里很棒

1
2
3
4
5
6
7
8
9
    function mh_exclude_featured_query( $query ) {  
    if(is_home()){
        if ( $query->is_home() ) {
            $feat = get_featured_post();
            $query->query_vars['post__not_in'] = array($feat->ID);
        }
    }
}
add_action( 'pre_get_posts', 'mh_exclude_featured_query' );

但是我也在尝试在category.php中做同样的事情,在那儿我将显示该类别中标有功能的最新帖子。 然后是下面的其余帖子,不包括精选帖子。

不幸的是,当我使用pre_get_posts过滤器尝试与上述相同的方法时,我陷入了无限循环并耗尽了内存。

1
2
3
4
5
if($query->is_category() && $query->is_main_query()){
    $cur_cat_id = get_cat_id( single_cat_title("",false) );
    $feat = get_featured_post($cur_cat_id);
    $query->query_vars['post__not_in'] = array($feat->ID);  
}

不知道我在做什么不同,导致内存耗尽。 category.php和index.php的结构几乎相同。


使用pre_get_posts过滤器:

1
2
3
4
5
6
7
8
9
10
11
12
<?php

function excludePostId($query) {
  $postIds = array(
    24, 10
  );

  if (is_category() && is_main_query()) {
    set_query_var('post__not_in', $postIds);
  }
}
add_action('pre_get_posts', 'excludePostId');

is_category()将接受类别标签或ID。 您可以限制帖子将被排除的类别。


添加此代码

1
2
3
   <?php if(!is_category('category_id')){
    echo 'Your Code Here';
    }?>