問題描述
Possible Duplicate:
How to know which one is the main query?
我很好奇知道什麼叫”main query”?
我在首頁有兩個查詢。
if (have_posts()) : while (have_posts()) : the_post();
// do the main loop
endwhile; endif;
$posts = new WP_Query(array('post_type' => 'some_other_post_type'));
while ($posts->have_posts()) : $posts->the_post();
// do the secondary loop
// but still operating with the some_post_type
endwhile; wp_reset_postdata();
而我想要的只是修改主查詢到我的自定義帖子型別的效率。
add_action( 'pre_get_posts', 'some_name');
function some_name($query) {
if (is_front_page() && is_main_query()) {
$query->set( 'post_type', 'some_post_type' );
return;
}
}
我認為那個鉤子中的條件只有在第一個迴圈中才是真的,但是似乎任何 new WP_Query
正在透過它。
你可以解釋一下,”main query” 是什麼?
PS:我已經找到 almost a similar question 與解決方案來改變 pre_get_post
鉤子中的查詢,透過自定義查詢 vars 。
最佳解決方案
您的過濾器有一個錯誤,即當您呼叫 is_main_query 時,您不檢查傳遞的查詢是否是主要查詢,檢查當前活動的查詢是否是主查詢,這將始終為真。
所以反而試試這個:
add_action( 'pre_get_posts', 'some_name');
function some_name($query) {
if ($query->is_front_page() && $query->is_main_query()) {
$query->set( 'post_type', 'some_post_type' );
return;
}
}
次佳解決方案
主要查詢是當 WordPress 確定要顯示請求 URI 時自動觸發的查詢。
WP_Query
的後續例項從不是主要查詢,但您可以使用它們來替換 $GLOBALS['wp_the_query']
中的主查詢結果。不要這樣做
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。