我从 Wordpress 搜索结果中排除任何帖子或将自定义分类法设置为特定术语的自定义帖子。我希望能够简单地添加更多分类法和术语(例如在数组中),而无需重复函数,并确保我能够高效地完成它。
谁能建议一个更清洁的功能来适应这个问题?
/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// Exclude Terms by ID from Search and Archive Listings
if ( is_search() || is_tax( 'marque' ) ) {
$tax_query = array([
'taxonomy' => 'site_search',
'field' => 'term_id',
'terms' => [ exclude_page ],
'operator' => 'NOT IN',
]);
$query->set( 'tax_query', $tax_query );
}
}, 11, 1 );
/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', function ( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// Exclude Terms by ID from Search and Archive Listings
if ( is_search() || is_tax( 'marque' ) ) {
$tax_query = array([
'taxonomy' => 'job_status',
'field' => 'term_id',
'terms' => [ closed ],
'operator' => 'NOT IN',
]);
$query->set( 'tax_query', $tax_query );
}
}, 11, 1 );
您可以尝试首先将数组中的所有数据定义为分类法/术语对(我已将数组嵌入到外部函数中,但可以直接在挂钩函数中添加)。这样您就可以轻松添加或删除数据。
然后我们使用 foreach 循环来读取和设置税务查询中的数据。所以你的代码将是这样的:
// HERE set in the array your taxonomies / terms pairs
function get_custom_search_data(){
return [
'site_search' => [ 'exclude_page' ],
'job_status' => [ 'closed' ],
];
}
/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', 'multiple_taxonomy_search', 33, 1 );
function multiple_taxonomy_search( $query ) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
// Exclude Terms by ID from Search and Archive Listings
if ( is_search() || is_tax( 'marque' ) ) {
// Set the "relation" argument if the array has more than 1 custom taxonomy
if( sizeof( get_custom_search_data() ) > 1 ){
$tax_query['relation'] = 'AND'; // or 'OR'
}
// Loop through taxonomies / terms pairs and add the data in the tax query
foreach( get_custom_search_data() as $taxonomy => $terms ){
$tax_query[] = [
'taxonomy' => $taxonomy,
'field' => 'slug', // <== Terms slug seems to be used
'terms' => $terms,
'operator' => 'NOT IN',
];
}
// Set the defined tax query
$query->set( 'tax_query', $tax_query );
}
}
代码位于活动子主题(或活动主题)的 function.php 文件中。未经测试,它应该可以工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)