Search code examples
phpwordpressformsquery-stringquery-variables

Wordpress how to use a second form that only searches for posts?


I have two forms on my wordpress site, search.blade.php and blog-search.blade.php.

search.blade.php is in the header of the site, and searches all content types.

blog-search.blade.php is meant to only search post types.

I'm using the following code to have it search for only blog posts:

    function searchfilter($query) {
 
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type', 'post');
    }
 
return $query;
}
 
add_filter('pre_get_posts','searchfilter');

Understandably, this applies to both search.blade.php AND blog-search.blade.php, but I only want it to apply to blog-search.

I think that if I added a conditional to check for the value of a hidden input that only exists on blog-search, I could get it to work, but I don't know how to do that.

Here's my blog-search.blade.php code:

<form action="{{ get_bloginfo('url') }}" method="GET" class="blog-search-form">
    <input type="search" name="s" placeholder="Search the blog...">
    <input type="hidden" name="search-type" value="normal" />
    <span class="icon-search"></span>
</form>

Is there a way I could implement something like:

 function searchfilter($query) {
 
    if ($query->is_search && !is_admin() && INPUT TYPE == HIDDEN ) {
        $query->set('post_type', 'post');
    }
    ...

So that only the blog-search searches through posts, and my main search works as usual? I tried implementing this, with no luck, so I'm thinking a conditional could help.

search.blade.php, just in case:

<form action="{{ get_bloginfo('url') }}" method="GET" class="search-form">
    <input type="search" name="s" placeholder="Search the site">
</form>

Solution

  • You could set this up in multiple ways. I personally always use ajax method to query a database, but if you would like to use query_vars method as you're already thinking about it and suggesting it in your question, then you could do something like this:

    So this would be your html form:

    <form method="GET">
        <input type="search" name="s" placeholder="Search the blog...">
        <input type="hidden" name="onlyblog" id="onlyblog" value="yes" />
        <span class="icon-search"></span>
        <button type="submit">Search</button>
    </form>
    

    then on the php side, your conditional check would for onlyblog value like so:

    function searchfilter($query) {
    
    $query_type = isset($_GET['onlyblog']) ? sanitize_text_field($_GET['onlyblog']) : "";
     
        if ($query->is_search && !is_admin() && !empty($query_type) && 'yes' == $query_type) {
            $query->set('post_type', 'post');
        }
     
    return $query;
    }
    

    Let me know if you were able to get it to work!