0

I have seen various ways to do this but none working 100% for me. I have a dropdown/select menu and users can choose multiple choices. This then sends an array of values that I want to query.

Either I can query each one individually but this isn't realistic because the array has many values and I would have to then cater for every single option eg:

'meta_query'    => array(
    'relation'      => 'OR',
    array(
        'key'       => 'location',
        'value'     => 'Melbourne',
        'compare'   => 'LIKE'
    ),
    array(
        'key'       => 'location',
        'value'     => 'Sydney',
        'compare'   => 'LIKE'
    )
)

I also tried to serialise the array like below, but this only works if I choose one option from the select menu. As soon as select multiple options I get an empty array as the response.

'value'   => serialize( $locations ),
'compare' => 'LIKE'

Finally, I tried a regex example I found but couldn't get that going either.

$field_value = sprintf( '^%1$s$|s:%2$u:"%1$s";', $locations, strlen( $locations ) );
'value' => $field_value,
'compare' => 'REGEXP'
2
  • 1
    If the meta value is a serialized string of an array like array( 'Melbourne', 'Sydney' ), then 'value' => '"(Melbourne|Sydney)"', 'compare' => 'REGEXP' would work. But then have you considered using a custom taxonomy named location instead?
    – Sally CJ
    Commented Jul 8, 2022 at 8:45
  • 1
    @SallyCJ, seriously. You are a legend! That works great. I wouldn't be able to create a taxonomy in this case, don't want to bore you with details! But, your solution is perfect. Would you be able to add it as an answer so I can mark as accepted answer? Commented Jul 8, 2022 at 9:09

1 Answer 1

1

As I commented, if the meta value is a serialized string of an array like array( 'Melbourne', 'Sydney' ), then 'value' => '"(Melbourne|Sydney)"', 'compare' => 'REGEXP' would work.

So there's no need for a complex regular expression pattern, and your meta_query could look like so where $locations is an array of locations:

'meta_query' => array(
    array(
        'key'     => 'location',
        'value'   => '"(' . implode( '|', $locations ) . ')"',
        'compare' => 'REGEXP',
    ),
),

Your Answer

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

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