让搜索支持所有自定义文章类型,搜索结果排除某些分类的文章,搜索结果排除所有页面
<?php
//让搜索支持所有自定义文章类型
function include_post_types_in_search($query) {
if (is_search()) {
$post_types = get_post_types(array('public' => true, 'exclude_from_search' => false), 'objects');
$searchable_types = array();
if ($post_types) {
foreach ($post_types as $type) {
$searchable_types[] = $type->name;
}
}
$query->set('post_type', $searchable_types);
}
return $query;
}
add_action('pre_get_posts', 'include_post_types_in_search');
//搜索结果排除某些分类的文章
function search_filter_category($query) {
if (!$query->is_admin && $query->is_search) {
$query->set('cat', ' , '); //分类的ID,前面加负号表示排除;如果直接写ID,则表示只在该ID中搜索
}
return $query;
}
add_filter('pre_get_posts', 'search_filter_category');
//搜索结果排除所有页面
function search_filter_page($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', 'search_filter_page');