我試圖從 WordPress 搜索結果中排除特定類別 ID。我已經嘗試使用這段代碼,我在互聯網上找到了幾個地方,但它似乎不起作用。我已將 ID 更改為正確的 ID。
function my_search_filter( $query ) {
if ( $query->is_search && !is_admin() )
$query->set( 'cat','-21' );
return $query;
}
add_filter( 'pre_get_posts', 'my_search_filter' );
現在我的解決方案是使用下面的代碼,我必須手動插入每個頁面 ID。它正在作業,但不是一個好的解決方案。
add_action('pre_get_posts','exclude_posts_from_search');
function exclude_posts_from_search( $query ){
if( $query->is_main_query() && is_search() ){
//Exclude posts by ID
$post_ids = array(52384,52366,52058,52392,52374);
$query->set('post__not_in', $post_ids);
}
}
是否可以將我當前的代碼與類別而不是每個頁面 ID 一起使用?或者第一個代碼示例是要走的路,但有一些變化?
uj5u.com熱心網友回復:
將以下函式放在您的活動主題functions.php 檔案中
function exclude_categories_from_search($query) {
// run query only if we are searching
if ( !$query->is_search )
return $query;
$term_ids = array( 19, 18, 214, 226, 20 ); add category/term ids
$taxquery = array(
array(
'taxonomy' => 'category', //Here add your taxonomy eg: category
'field' => 'id',
'terms' => $term_ids,
'operator'=> 'NOT IN'
)
);
$query->set( 'tax_query', $taxquery );
}
add_action( 'pre_get_posts', 'exclude_categories_from_search' );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342806.html
標籤:php WordPress的 搜索
上一篇:獲取與分類法關聯的用戶串列
下一篇:MYSQLDB-隨機創建新表
