Removing “s” from search with custom parameters

I’m trying to do something that I thought would be quite simple and has turned out to be not simple at all. I’ve seen quite a few posts that look similar at first glance but none solve the issue for me.

I’ve built a custom searchform with 3 select fields. One is pre-populated with a custom taxonomy and two are populated with DISTINCT values from custom fields.

Read More

I also have the standard input field:

<input type="hidden" value="search" id="s" name="s">  

so that when the form is submitted it goes to search.php

This form is searching one custom post type only and the search could be only one select field or all three.

I’ve amended the main query on search.php using pre_get_posts and built in if statements to allow one or more select fields from the form to be used.

This is my function in functions.php

// advanced search functionality
function advanced_search_query($query) {

    if( ! is_admin() && $query->is_main_query() && $query->is_search() ) {

        // Force to only search directory
        $query->set('post_type', 'directory');

        //area search
        if ( isset ( $_GET['a'] ) ) {
            $query->set( 'meta_key', 'area-2' );
            $query->set( 'meta_value', $_GET['a'] );
        }


        //types term search
        if ( isset ( $_GET['t'] ) ) {
            $query->set( 'types', $_GET['t'] );
        }

        //price search
        if ( isset ( $_GET['p'] ) ) {
            $query->set( 'meta_key', 'price' );
            $query->set( 'meta_value', $_GET['p'] );
        }

        return $query;
    }

}

add_action('pre_get_posts','advanced_search_query');

The problem is, that the hidden field value for ‘s’ which is ‘search’ always affects the results. It shows in the breadcrumb and I don’t get any results because none match the specific custom fields/taxonomy and ‘search’.

I’ve tried including ‘s’ as one of the names of my select fields but its not specific enough. I need the selected search parameter to only search for results that match the criteria exactly. for example: an area of Deansgate must only match posts with a custom field value of Deansgate.

The ‘s’ field is too general so, my question is can I remove it from the query completely once we have reached the search.php template?

Thanks in advance 🙂

Related posts

Leave a Reply