我目前正在使用以下内容过滤“全部”,“页面”和“帖子”之间的搜索结果(来自:https://inspirationalpixels.com/search-results-filter-wordpress/)。如何更改它,使其不显示所有结果。我希望它首先显示页面搜索结果,然后为帖子提供过滤器选项。
对于我主题的functions.php:
function ip_search_filter_item_class($passed_string = false) {
$post_type = (isset($_GET['post_type']) ? $_GET['post_type'] : false);
if($passed_string == $post_type) {
echo 'current';
}
}
function ip_search_filter($query) {
// Check we're not in admin area
if(!is_admin()) {
// Check if this is the main search query
if($query->is_main_query() && $query->is_search()) {
// Check if $_GET['post_type'] is set
if(isset($_GET['post_type']) && $_GET['post_type'] != '') {
// Filter it just to be safe
$post_type = sanitize_text_field($_GET['post_type']);
// Set the post type
$query->set('post_type', $post_type);
}
}
}
// Return query
return $query;
}
add_filter('pre_get_posts', 'ip_search_filter');
对于我主题的search.php:
<a class="<?php echo (!isset($_GET['post_type']) ? 'current' : false); ?>" href="<?php echo home_url(); ?>?s=<?php echo get_search_query(); ?>">
All
</a>
<a class="<?php ip_search_filter_item_class('post'); ?>" href="<?php echo home_url(); ?>?s=<?php echo get_search_query(); ?>&post_type=post">
Posts
</a>
<a class="<?php ip_search_filter_item_class('page'); ?>" href="<?php echo home_url(); ?>?s=<?php echo get_search_query(); ?>&post_type=page">
Pages
</a>
答案 0 :(得分:0)
我解决了。我需要做的就是在函数中将查询类型设置为 page ,然后删除第二个过滤器选项,并重命名第一个过滤器。
功能更改为:
function ip_search_filter($query) {
// Check we're not in admin area
if(!is_admin()) {
// Check if this is the main search query
if($query->is_main_query() && $query->is_search()) {
$query->set('post_type','page');
// Check if $_GET['post_type'] is set
if(isset($_GET['post_type']) && $_GET['post_type'] != '') {
// Filter it just to be safe
$post_type = sanitize_text_field($_GET['post_type']);
// Set the post type
$query->set('post_type', $post_type);
}
}
}
// Return query
return $query;
}
add_filter('pre_get_posts', 'ip_search_filter');
搜索模板已更改为:
<div class="filter-by">Filter By:</div>
<a class="<?php echo (!isset($_GET['post_type']) ? 'current' : false); ?>" href="<?php echo home_url(); ?>?s=<?php echo get_search_query(); ?>">Programs, Offices, Locations</a>
<a class="<?php ip_search_filter_item_class('post'); ?>" href="<?php echo home_url(); ?>?s=<?php echo get_search_query(); ?>&post_type=post">Search News</a>