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