問題描述

我正在閱讀 Stephen Harris 對於使用 WP_query()query_posts()pre_get_poststhis question 的極好答案。

他說 「pre_get_posts 是一個過濾器,用於更改任何查詢,最常用於更改’main query’ 。」

可以使用 pre_get_posts 過濾僅使用 WP_Query 建立的特定輔助查詢?例如。

$my_secondary_loop = new WP_Query(...);
if( $my_secondary_loop->have_posts() ):
    while( $my_secondary_loop->have_posts() ): $my_secondary_loop->the_post();
       //The secondary loop
    endwhile;
endif;
wp_reset_postdata();

任何幫助非常感謝。

最佳解決方案

最簡單的方法是立即在查詢之前新增動作和 remove it

add_action('pre_get_posts', 'some_function_in_functionsphp');
$my_secondary_loop = new WP_Query(...);
remove_action('pre_get_posts', 'some_function_in_functionsphp');

if( $my_secondary_loop->have_posts() ):
    while( $my_secondary_loop->have_posts() ): $my_secondary_loop->the_post();
       //The secondary loop
    endwhile;
endif;
wp_reset_postdata();

編輯

您可以使用的另一種技術是設定您自己的查詢 var 並在鉤子中檢查:

// tell WordPress about our new query var
function wpse52480_query_vars( $query_vars ){
    $query_vars[] = 'my_special_query';
    return $query_vars;
}
add_filter( 'query_vars', 'wpse52480_query_vars' );

// check if our query var is set in any query
function wpse52480_pre_get_posts( $query ){
    if( isset( $query->query_vars['my_special_query'] ) )
        // do special stuff

    return $query;
}
add_action( 'pre_get_posts', 'wpse52480_pre_get_posts' );

並在模板中:

// set the query var (along with whatever others) to trigger the filter
$args = array(
    'my_special_query' => true
);
$my_secondary_loop = new WP_Query( $args );

次佳解決方案

pre_get_posts fires for every post query:

  • get_posts()
  • new WP_Query()
  • That random recent posts widget your client installed without you knowing.
  • Everything

— @nacin

除非你排除你的過濾器,否則使用條件:is_main_query(),那麼你的過濾器將觸發你的新 WP_Query 。

如果你只想要定位你特定的新 WP_Query,那麼沒辦法。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。