3
votes

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>
1

1 Answers

1
votes

I worked it out. All I needed to do was set the query type to page in my functions, and then remove my second filter option, and rename the first filter.

Functions changed to:

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');

Search templated changed to:

 <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>