問題描述
我有一個顯示 home.php 模板的主頁,其中包含 2 個帶有小工具的側邊欄。
主要的查詢仍然是標準的 10 個帖子,但是由於我沒有顯示這些資訊,所以我想徹底消除對資料庫的查詢。如果需要的話,一個空的迴圈將會做,因為我沒有使用 home.php 模板中的主迴圈。
我該怎麼做?我可以使用 pre_get_posts 來最大限度地減少和減少查詢,但仍然讓我有一個非常快的查詢,我該如何完全消除它?
最佳解決方案
posts_request 過濾器
透過 WP_Query 掃描,我們發現這一部分感興趣:
if ( !$q['suppress_filters'] ) {
/**
* Filter the completed SQL query before sending.
*
* @since 2.0.0
*
* @param array $request The complete SQL query.
* @param WP_Query &$this The WP_Query instance (passed by reference).
*/
$this->request = apply_filters_ref_array( 'posts_request',
array( $this->request, &$this ) );
}
if ( 'ids' == $q['fields'] ) {
$this->posts = $wpdb->get_col( $this->request );
$this->posts = array_map( 'intval', $this->posts );
$this->post_count = count( $this->posts );
$this->set_found_posts( $q, $limits );
return $this->posts;
}
我們可能會嘗試透過 posts_request 過濾器消除主要的家庭請求。以下是一個例子:
add_filter( 'posts_request', function( $request, WP_Query $q )
{
// Target main home query
if ( $q->is_home() && $q->is_main_query() )
{
// Our early exit
$q->set( 'fields', 'ids' );
// No request
$request = '';
}
return $request;
}, PHP_INT_MAX, 2 );
在那裡我們迫使'fields' => 'ids'提前退出。
posts_pre_query 過濾器 (WP 4.6+)
我們還可以使用新的 posts_pre_query src 濾鏡,可在 WordPress 4.6+
add_filter( 'posts_pre_query', function( $posts, WP_Query $q )
{
if( $q->is_home() && $q->is_main_query() )
{
$posts = [];
$q->found_posts = 0;
}
return $posts;
}, 10, 2 );
此過濾器可以跳過通常的資料庫查詢來實現自定義帖子注入。
我剛剛測試了這一點,注意到這不會阻止貼上的帖子,與 posts_request 方法相反。
檢視更多資訊 #36687 的機票和 @boonebgorges 的 example there 。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。