1 回答

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個贊
要根據(jù)查詢 CPT 添加其他條件查詢參數(shù),我們可以使用 pre_get_posts 掛鉤來執(zhí)行此操作,就像您所做的那樣。
檢查查詢是否針對 CPT
我們將創(chuàng)建一個自定義函數(shù),該函數(shù)將掛鉤此操作并檢查 $query 是否包含 CPT,如果包含,則添加額外的參數(shù)。正如您所想的那樣,這將起作用:
add_action( 'pre_get_posts', 'add_cpt_query_args');
function add_cpt_query_args( $query ) {
// If this isn't the main search query on the site, then do nothing.
if( is_admin() || !$query->is_search() || !$query->is_main_query() )
return;
// Check if the query is for any of our CPTs
if (in_array ( $query->get( post_type'), array('YOUR_CPT_SLUG', 'ANOTHER_CPT') ) ){
// set the args for this CPT
$query->set( 'posts_per_page', 1 );
$query->set( 'orderby', 'rand' );
}
}
檢查多個 CPT 和不同的查詢參數(shù)
由于您想要對多個 CPT 執(zhí)行此操作并為它們提供不同的參數(shù)(例如 posts_per_page),因此您必須為每個 CPT 添加單獨(dú)的 if在上面的代碼中。
更靈活且可維護(hù)的方法 執(zhí)行此操作是使用數(shù)組將每個 CPT 的所有查詢參數(shù)信息保存在數(shù)組中。這意味著:
我們可以簡單地循環(huán)遍歷它以使用添加查詢參數(shù) - 無需添加額外的if檢查每個要檢查的 CPT
我們可以根據(jù)需要為每個 CPT 添加任意數(shù)量的查詢參數(shù)(例如 pages_per_post、order_by 等),每個 CPT 可以有不同的查詢參數(shù)args,并且不必將它們硬編碼到代碼中,或者手動檢查我們是否有它們的值。
我們可以使用此代碼來做到這一點(diǎn) - 下面有對其工作原理的完整說明 (注意 - 這未經(jīng)測試,但基本邏輯已經(jīng)存在!):
add_action( 'pre_get_posts', 'add_cpt_query_args');
function add_cpt_query_args( $query ) {
// If this isn't the main search query on the site, then do nothing.
if( is_admin() || !$query->is_search() || !$query->is_main_query() )
return;
// As you want to do this for multiple CPTS, a handy way to do this is set up all the info in an array
$CPT_args['qcm'] = array('posts_per_page'=> 1, 'orderby' => 'rand');
$CPT_args['anotherCPT'] = array('posts_per_page'=> 5, 'orderby' => 'date', 'order => 'ASC'');
// Now check each CPT in our array to see if this query is for it
foreach ($CPT_args as $cpt => $query_args ){
if (in_array ( $query->get( post_type'), array($cpt) ) ){
// this query is for a CPT in our array, so add our query args to the query
foreach ($query_args as $arg => $value )
$query->set( $arg, $value );
}
}
}
這是如何運(yùn)作的
1。檢查這是否是主站點(diǎn)上的主要搜索查詢 - 如果不是(并且我們沒有其他條件),最干凈的方法是在此時簡單地結(jié)束該函數(shù),那么我們就不會嘗試在 中保留大量代碼if
if( is_admin() || !$query->is_search() || !$query->is_main_query() )
return;
2.在數(shù)組中設(shè)置 CPT 參數(shù) - 因?yàn)槟雽Χ鄠€ CPT 執(zhí)行此操作,最簡單的方法是將所有信息存儲在一個數(shù)組中,我們可以在數(shù)組中簡單地使用該數(shù)組循環(huán)。
在此示例中,我們將使用一個名為 $CPT_args 的數(shù)組,并為我們要檢查的每個 CPT 添加一個條目,并以 CPT 名稱作為鍵。一個>
我們將使用另一個數(shù)組作為值,這將包含您想要添加到此 CPT $query 的所有參數(shù),例如
$CPT_args['qcm'] = array('posts_per_page'=> 1, 'orderby' => 'rand');
使用此數(shù)組可將所有參數(shù)信息保存在一個位置,并且可以輕松添加或刪除更多 CPT 條件,而不會影響影響查詢的主代碼。
3.檢查 $query 是否適用于任何 CPTS,方法是循環(huán)遍歷我們的數(shù)組并根據(jù)我們的鍵檢查查詢 post_type $CPT_args數(shù)組:
foreach ($CPT_args as $cpt => $query_args ){
if (in_array ( $query->get( post_type'), array($cpt) ) ){
...
}
}
4。如果此查詢針對的是 CPT,請將 CPT 的查詢參數(shù)添加到 $query。我們可以簡單地查看我們的參數(shù)數(shù)組并將它們添加到 $query。
foreach ($queryargs as $arg => $value )
$query->set( $arg, $value );
- 1 回答
- 0 關(guān)注
- 157 瀏覽
添加回答
舉報