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.
– Julio Cesar