Search multiple custom fields by using meta_query

The question:

I’m trying to create a search results listing for a custom post type and the problem I’m running in to is with the way the ‘meta_query’ parameter is stringing the passed values together. It appears to be treating each ‘meta_query’ value as an ‘AND’ rather than ‘OR’. Here is the code I’m using:

$strsearch = 'lorem';
$args = array(
    'post_type' => 'products',
    'meta_query' => array(
        array('key' => '_product_make','compare' => 'LIKE','value' => $strsearch),
        array('key' => '_product_model','compare' => 'LIKE','value' => $strsearch)
        )
    ,'s' => $strsearch);
$resource_query = new WP_Query($args);

When I search anyone of the fields individually I get the desired results. When I use them together it comes up as not found since the string I’m searching for may only occur in one of the three fields listed below. Is there any way to have ‘meta_query’ treat each of the passed field comparisons as ‘OR’?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Yes, since WP 3.2 you can set the ‘relation’ arg:

'meta_query' => array(
    'relation' => 'OR',
    array('key' => '_product_make','compare' => 'LIKE','value' => $strsearch),
    array('key' => '_product_model','compare' => 'LIKE','value' => $strsearch)
)

See http://core.trac.wordpress.org/ticket/17011


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment