5

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

1

1 Answer 1

8

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

5
  • Is it possible to do now? I've looked at the ticket and it seems to say "solved", but I can't figure out what to add to make it work. Would really appreciate any help. Thanks :)
    – dashaluna
    Jun 30, 2011 at 10:38
  • 1
    Updated answer.
    – scribu
    Jun 30, 2011 at 11:09
  • @dashaluna: You're welcome. Note that on this site, the appropriate response is to upvote the answer. :)
    – scribu
    Jun 30, 2011 at 11:40
  • when i use this it seems to not search the normal fields? Seems 's' => $strsearch is ignored completely but 'relation' => 'OR' works perfectly with the meta_keys... Is it possible to search the default fields too? (title etc)
    – v3nt
    Jul 24, 2012 at 14:45
  • I wonder if this will match searches like this: A post with: custom_field_1 contains the word cats custom_field_2 contains the word dogs Someone searches for ats ogs and the post is returned.
    – Nathan
    Apr 26, 2016 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.