I have to check if word the user is looking for is also contained in a ACF custom fields. So I modify the standard query to search also into meta_query field I need:
function modifica_search( $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
$meta_query = array(
array(
'key' => 'contenuto',
'value' => sanitize_text_field( $_GET['s']),
'compare' => 'LIKE'
)
);
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'modifica_search' );
but printng out the query (for ?s=milano)I notice that there is an AND operator (the bold one) where I need an OR :
... WHERE 1=1 AND (((nctm_posts.post_title LIKE '%milano%') OR (nctm_posts.post_excerpt LIKE '%milano%') OR (nctm_posts.post_content LIKE '%milano%'))) AND (( nctm_postmeta.meta_key = 'contenuto' AND nctm_postmeta.meta_value LIKE '%milano%' ) ...
how can I solve this?
I have to check if word the user is looking for is also contained in a ACF custom fields. So I modify the standard query to search also into meta_query field I need:
function modifica_search( $query ) {
if ( $query->is_search() && $query->is_main_query() ) {
$meta_query = array(
array(
'key' => 'contenuto',
'value' => sanitize_text_field( $_GET['s']),
'compare' => 'LIKE'
)
);
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'modifica_search' );
but printng out the query (for ?s=milano)I notice that there is an AND operator (the bold one) where I need an OR :
... WHERE 1=1 AND (((nctm_posts.post_title LIKE '%milano%') OR (nctm_posts.post_excerpt LIKE '%milano%') OR (nctm_posts.post_content LIKE '%milano%'))) AND (( nctm_postmeta.meta_key = 'contenuto' AND nctm_postmeta.meta_value LIKE '%milano%' ) ...
how can I solve this?
Share Improve this question asked Jan 23, 2017 at 18:27 fabiofabio 1031 silver badge5 bronze badges 1- Look also this plugin: ACF: Better Search – Mateusz Gbiorczyk Commented Jun 16, 2017 at 15:42
1 Answer
Reset to default 0I'm typically against using a bunch of plugins, but an option for you is to use the Relevanssi plugin. I use it along side ACF and allows you to search within those fields.
If you decide to use it, after installation/activation, go to the setting page for the plugin and scroll down to the "Indexing Options" section and under that there is a field called, "Custom fields to index". You have a few options. Here's the description from the plugin itself:
A comma-separated list of custom fields to include in the index. Set to 'visible' to index all visible custom fields and to 'all' to index all custom fields, also those starting with a '_' character.
I typically set it to "visible" so it'll search all of my visible custom fields.
Hope this helps.