Tips on how to make a search field with Wordpress

0

I need tips on how to create a search field in Wordpress, I have a little knowledge on the platform but still very limited and I do not know where to start.

The search field is composed of state, city and neighborhood, I read several tutorials teaching how to make a search field, but none of them (which I have found) explains how to do a search with more than one field. This state, city, and neighborhood information is tracked by custom fields in a post_type that I've created.

I do not have code yet, because I really do not know where to start. I need tips, information, links, anything that gives me a "north".

    
asked by anonymous 02.06.2017 / 03:05

1 answer

2

The standard WordPress search always begins with a GET request containing the s key:

www.example.com/?s=gatinhos

Search for "kittens" in the bank. The default search only looks up the data in the post_title and post_content fields of the Post and Page .

Beauty, then to search the additional fields you need to intercept this search before it reaches the bank and send the required information:

add_action( 'pre_get_posts', 'intercepta_busca' );

The action pre_get_posts runs before queries so we delimit what you want inside it:

function intercepta_busca( $query ) {

    if( is_admin() ) {
        return;
    }

    if( $query->is_main_query() && $query->is_search() ) {
        // pronto, agora sabemos que as modificações só ocorrerão
        // na consulta principal dentro de uma busca no front-end:

        $query->set( 'post_type', array( SEU_POST_TYPE ) );
        $query->set( 'meta_query', array(
            'relation' => 'OR' // aceita AND/OR: use somente se tiver mais de 1 campo
            array(
                'key' => NOME_DO_CAMPO,
                'value' => $query->query_vars['s']
            ),
            // se for buscar por mais campos, inclua um array 
            // para cada par key/value
            array(
                'key' => NOME_DO_OUTRO_CAMPO,
                'value' => $query->query_vars['s']
            ),
        ) );
    }

}

And that's it. In the above example the search will return all posts in SEU_POST_TYPE containing the search term in title or body E in NOME_DO_CAMPO or NOME_DO_OUTRO_CAMPO

    
02.06.2017 / 12:05