How can I have Multiple Post-Type Specific Search Results in WordPress?

January 9, 2017

There may come a time when you need to build out multiple types of searches on your WordPress website. For example, you might want to have a general search in the header and a blog posts specific search on your blog page that each need to go to the search results page displaying different results.

Here are the 3 simple steps that can accomplish this:

1) Add a hidden input element into the search form, like so:

<div class="search" role="search">
    <form method="get" id="searchform" class="searchform" action="<?php bloginfo('url'); ?>/">
         <input class="resultSearch" type="text" value="" name="s" id="blogS" placeholder="Search Articles"/>
         <input type="hidden" name="search-type" value="blog" />
         <input name="submit" type="submit" value="" aria-label="Submit Search" />
    </form>
</div>

The input should have a name and custom value associated with it. In this case our name is “search-type” and our value is “blog”.

2) Add a filter to your functions.php

function mySearchFilter($articleQuery) {
    if( isset($_GET['search-type']) && $_GET['search-type']){
        $type = $_GET['search-type'];
    }
    if ($articleQuery->is_search && $type == 'blog') {
        $articleQuery->set('post_type', 'post');
    };
    return $articleQuery;
};

add_filter('pre_get_posts','mySearchFilter');

This is saying if we have a search-type and the search type-type = blog, then filter the results before we even load them onto the search page. It is limiting the results to only show posts of ‘post_type’ = ‘post’. You could set this to be any post type.

3) The last part is editing the search.php template to display different information based on what the search-type is. You can do this by using the following conditional:

<?php if(isset($_GET['search-type'])) {
    $type = $_GET['search-type'];
    if($type == 'blog') {?>
    //ARTICLE SEARCH 
<?php
    } else  {?> 
    //GLOBAL SEARCH
 }
?>

This allows you to edit the HTML or PHP associated with each of the different types of searches you have using only the search.php template.

Using this method there are many more possibilities for how to structure your multiple search results in WordPress.

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive