Search multiple custom fields by using meta_query

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’?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments