0

Already got some clues on how to do this,

see here: meta_query with array as value

but i am confused over multiple meta_queries like this:

for ($i=0; $i< count($amenities); $i++)
    {
        $count = count($arrays);
        $arrays[$count] = array(
                    'key' => 'amenities',
                    'value' => $amenities[$i],
                    'compare' => 'LIKE'
                    );
    }

for ($j=0; $j< count($amenities2); $j++)
    {
        $count2 = count($arrays2);
        $arrays2[$count2] = array(
                    'key' => 'amenities',
                    'value' => $amenities[$j],
                    'compare' => 'LIKE'
                    );
    }

then how to include $arrays2 in below query with 'relation' => 'AND'?

$the_query = new WP_Query(array(
        'post_type' => 'listing',
        'post_status' => 'publish', 
        'category_name' => 'private_rental',
        'meta_query' => $arrays
    ));
1

The default relation is AND so you really don't need to specify that, but I'll show you how to do it anyway.

Really, you just have an array manipulation problem.

$amenities = array('a','b','c');
$amenities2 = array('d','e','f');
foreach ($amenities as $a)
{
  $arrays[] = array(
              'key' => 'amenities',
              'value' => $a,
              'compare' => 'LIKE'
              );
}

foreach ($amenities2 as $a2)
{
  $arrays2[] = array(
              'key' => 'amenities',
              'value' => $a2,
              'compare' => 'like'
              );
}
$meta_query = array('relation' => 'AND');
$meta_query[] = $arrays;
$meta_query[] = $arrays2;
var_dump($meta_query);

I also cleaned up your code. It was overly complicated and broken. The if statements were overkill for iterating over an array and the $count = count($arrays); lines were unnecessary and didn't do anything as you were counting the arrays before they were created. Even if it worked, you had the possibility of clobbering one value with another. If the counts were equal you'd end up overwriting part of the array, not adding to it.

Of course, that is not the only way to put together the final array. In fact, that is probably not the way I'd do it if it were my code. That is probably the easiest way to demonstrate things though.

  • Isn't your output an array with two multidimensional arrays inside of it? Shouldn't you use array_merge to add $arrays and $arrays2? – Jake Mar 14 '14 at 1:25

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.