Tips on how to make a search field with Wordpress

Asked

Viewed 1,685 times

1

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 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 (that I have found) explains how to do a search with more than one field. This state, city and neighborhood information is registered by custom fields in a post_type that I created.

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

1 answer

3


Standard Wordpress search always starts with a request GET containing the key s:

www.example.com/?s=gatinhos

does a search for "kittens" in the database. The default search only searches the data in the fields post_title and post_content of types Post and Page.

All right, so to search the additional fields you need to intercept this search before it reaches the bank and sends the necessary information:

add_action( 'pre_get_posts', 'intercepta_busca' );

The action pre_get_posts wheel before wheels the consultations so we delimit what we 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 done. In the example above the search will return all posts in SEU_POST_TYPE containing the search term on the title or body E in NOME_DO_CAMPO or NOME_DO_OUTRO_CAMPO

  • Perfect, Ricardo. This is what I needed, I will implement following your recommendation. I humbly thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.