I am using the following to currently filter search results between All, Pages, and Posts (from: https://inspirationalpixels.com/search-results-filter-wordpress/). How can I change it so it does not display the ALL results. I want it to display the pages search results first, and then provide the filter option for posts.
For my theme's 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');
For my theme's 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>