0

I need to do multiple meta query from my array. I have something like this:

$search_term[] = array(
  'key' => '_cmb_listing_status',
  'value' => 'Active',
  'compare' => '='
);
foreach ( $refine_property_type as $search_value ) {
    $search_term[] =
            array(
                'key' => '_cmb_property_type',
                'value' => $search_value,
                'compare' => '='
            );
}

And that gives output like this:

Array (
[0] => Array
    (
        [key] => _cmb_listing_status
        [value] => Active
        [compare] => =
    )

[1] => Array
    (
        [key] => _cmb_property_type
        [value] => House
        [compare] => =
    )

[2] => Array
    (
        [key] => _cmb_property_type
        [value] => Office
        [compare] => =
    )
)

I am doing meta query in worpdress with this code:

$args = array(
'paged' => $paged,
'post_type' => 'property',
'posts_per_page' => 5,
'meta_key' => '_cmb_listing_featured',
'orderby' => 'meta_value',
'order' => 'DESC',
'meta_query' => array(
    'relation' => 'AND',
     $search_term
    )
);
$wp_query = new WP_Query( $args );

And it just won't work ? Can anyone help me out to figure this out? I think it's because the multidimensional array is being passed into the query, but I am not sure how to "flatten" it inside WP_Query ?

1

$search_term is already an array of an array. When you eventually add that to your meta_query, you get an array of an array of an array, which will not work

You are using AND as your relation operator which is the default for a multi-array meta_query. I would suggest that you drop that, and then simply just feed $search_term directly to your meta_query. No arrays.

Example

'meta_query' => $search_term,
  • And is there a way to change relation operator to "OR" ? – Peter Nov 6 '14 at 6:21
  • Yes. You need to add that to your $search_term array. I'm thinking like using array_unshift to add that key/value pair to the array. relation would be your key while OR will be the value. – Pieter Goosen Nov 6 '14 at 6:52
  • Thanks Pieter, after some goggling I realized that I'll have to mix "AND" and "OR" relation operators and since that's not possible I'll write my own SQL queries. Thanks for the help ! – Peter Nov 6 '14 at 7:01
  • My pleasure, and good luck with your project. :-) – Pieter Goosen Nov 6 '14 at 7:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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