WP extend search to post meta with pre_get_posts filter

i’m trying to extend wp search to postmeta. this is my snippet:

function filtroRicerca($query) {

    if ($query->is_search):

        $post_type = $query->get('post_type');
        $post_type[] = 'ordine';
        $query->set('post_type', $post_type );

        $meta_query = $query->get('meta_query');
        $meta_query['relation'] = 'OR';
        $meta_query[] = array(
                'key' => 'ritiro_indirizzo',
                'value' =>  $query->query_vars['s'],
                'compare' => 'LIKE'
        );
        $query->set( 'meta_query', $meta_query );

    endif;

    return $query;
};

add_filter('pre_get_posts','filtroRicerca');

this should be quite easy, but i can’t see where i’m wrong! if i search for a string, results fetched only match post title, content, etc. if i look for something only in my meta field no rows come back. what i’m doing wrong?

Related posts

Leave a Reply

1 comment

  1. There is a WP bug, you need to encapsulate in another array the $meta_query[] = like:

     $meta_query[] = array(
     array(
                'key' => 'ritiro_indirizzo',
                'value' =>  $query->query_vars['s'],
                'compare' => 'LIKE'
        )
     );
    

    Also, you don’t need to return the $query object.