pre_get_posts Action主要用來修改主查詢,經(jīng)常在需要修改主文章查詢時使用,可以讓我們不用創(chuàng)建自定義查詢來得到我們需要的文章內(nèi)容。
參數(shù)
該Action只有一個參數(shù),就是通過引用傳遞的$wp_query 對象。
使用示例
下面是幾個使用示例,可以幫我我們快速了解 pre_get_posts Action 的使用方法。
在首頁文章中排除ID位7、11 的文章。
add_action( 'pre_get_posts', function ($query) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'post__not_in', array( 7, 11 ) );
}
} );
在搜索結果中排除頁面、只搜索文章內(nèi)容。
add_action( 'pre_get_posts', function ($query) {
if ( ! is_admin() && $query->is_main_query() ) {
if ( $query->is_search ) {
$query->set( 'post_type', 'post' );
}
}
} );