簡體   English   中英

如何從wordpress中的category.php查詢中排除id的帖子

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

我有一個模板,其中有一個主要的最新特色帖子(標記為特色),然后還有8個以下。 在主頁上,我能夠查詢最新的精選帖子,然后將其id傳遞給pre_get_posts wordpress過濾器中的函數。 它在那里很棒

    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過濾器嘗試與上面相同的方法時,我陷入了無限循環並且內存不足。

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過濾器:

<?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()將接受類別slug或ID。 您可以限制帖子將被排除在哪些類別之外。

添加此代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM