Question

I am trying to customize the search.php in a way so it can also show the posts which has search keyword in meta key values. Please note: I am using Advance Custom Field Plugin which uses meta keys.

For example I have a meta key called "treatments" and if user input "my treatment" in search bar and hit search button, I want to show the posts which has "my treatment" keyword its contents and/or the posts which has "my treatment" in its meta key called "treatments".

I want to work it with multiple meta keys at same time e.g. "address". I wrote following code but it just break the search. Can any one please tell me what I am doing wrong.

$args = array(
        'post_type'=> 'beauty_salon',
        's' =>$s,
        'meta_query' => array(
               array(
                  'key' => 'treatments',
                  'value' => $s,
                  'compare' => 'LIKE',
                ),
                array(
                  'key' => 'address',
                  'value' => $s,
                  'compare' => 'LIKE',
                ),
        ),
    );
    $query = new WP_Query( $args );

    // The Loop.......etc

Please note: I need short custom code so please do not suggest a plugin. I know there are many to do the same.

Was it helpful?

Solution

Try using the 'relation' option for meta_query.

Also I suggest for you to use the pre_get_posts fiter to "hack" into the search query if you are using the actual search.php template to display the search items so you would write in your functions.php instead of the template file something like this:

function search_filter($query) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search) {
            $meta_args = array(
                'relation' => 'OR',
                array(
                    'key' => 'treatments',
                    'value' => $s,
                    'compare' => 'LIKE',
                ),
                array(
                    'key' => 'address',
                    'value' => $s,
                    'compare' => 'LIKE',
                ),
            );

            $query->set('post_type', 'beauty_salon');
            $query->set('meta_query', $meta_args);
        }
    }
}

add_action('pre_get_posts','search_filter');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top