我使用下面的函數目前不包括在我的主頁循環「特色」的類別的所有訊息:僅使用pre_get_posts排除Wordpress主循環中類別的最新帖子?
function main_loop_excludes($query){
if($query->is_main_query() && $query->is_home()){
//'featured' cat ID = 531
$query->set('cat','-531');
}
}
add_action('pre_get_posts','main_loop_excludes');
這工作完全,但我想只篩選出最近張貼而不是所有帖子從'精選'類別。這可能嗎?
我已經看到了使用WP_Query
來過濾特定帖子的方法,但我正在尋找一種方法在主要的Wordpress循環中執行此操作。 pre_get_posts
感覺是最好的起點。我在正確的軌道上嗎?
編輯:
我用下面的代碼保存在特定的文章中,我要排除的ID(保存爲變量$post_to_exclude_ID
):
$post_ids = get_posts(array(
'numberposts' => -1, // get all posts.
'category_name' => 'featured',
'fields' => 'ids', // Only get post IDs
));
// post ID = 2162
$post_to_exclude_ID = $post_ids[0]; // Save ID of most recent post
現在我可以使用原始main_loop_excludes
函數來過濾主循環,以顯示只有有問題的帖子,但我似乎無法逆轉過程。在ID打破功能之前添加一個減號(該循環會顯示全部帖子)。
新功能:
function main_loop_excludes($query){
if($query->is_main_query() && $query->is_home()){
// Make sure the var is accessible
global $post_to_exclude_ID;
// Set the filter
$query->set('p', $post_to_exclude_ID);
}
}
add_action('pre_get_posts','main_loop_excludes');
這並不不工作:
$query->set('p', '-2162');
但同樣的代碼風格確實爲類別工作:
$query->set('cat','-531');
NB:謝謝到Valerius用於提示找到帖子ID並將其注入$query->set...
的想法。
我無法獲得此代碼的工作:不斷得到死亡的白色屏幕。 'wp_get_recent_posts'確實讓我發現了我用來查找所需ID的'get_posts'數組方法,所以感謝:主要問題被編輯以顯示我現在在哪裏。越來越近,我希望... –
對我而言混亂,對不起。 'p'參數不可用。但是,post__not_in是(注意:名稱中的雙下劃線)。它需要一個包含post ID的整數排除。上面更新了我的代碼示例。 – Valerius
'post__not_in'解決了問題!然而,不是馬上:'wp_get_recent_posts(...'部分不斷給我提供死亡的白色屏幕,使用問題中概述的'get_posts'方法*工作,並通過'post__not_in'傳遞完美! –