Query multiple meta values

I’m working on a ‘checkbox filter’ to query posts by checked values. See this link (EDIT: As you can see there are just 2 posts in this link, as soon as the user checks for ‘MINI’ it gets a good result, as soon as the user checks ‘MINI’ and ‘COMPACT’, it gives no results instead of the 2 posts). Now it works if the user only checks 1 value. As soon as the user the checks more then one it will give no results. I’m using following meta query code (it’s part of a longer code, that’s why there is the if statement):

if (gap_meta_values($key, $value)) {
            $args['meta_query'][] = array(
                'key' => $key,
                'value' => $value,
                'compare' => 'LIKE'

            );

So this works if there is only 1 meta value. However if there are more than one values it does not work. So I tried several things to get it work, I tought it was because there’s no relation between the key and value. So I tried this:

Read More
if (gap_meta_values($key, $value)) {
            $args['meta_query'][] = array(
            'relation' => 'OR',
                array (
                'key' => $key,
                'value' => $value,
                'compare' => 'LIKE'
                )

        );
        }

But this neither seem to work. How to make this works so it will query all posts from the checked values? Thanks for your response.

Related posts

1 comment

  1. You code is generating a broken meta_query. You code will produce something like this:

    array(1) {
      ["meta_query"]=>
      array(2) {
        [0]=>
        array(2) {
          ["relation"]=>
          string(2) "OR"
          [0]=>
          array(3) {
            ["key"]=>
            string(4) "test"
            ["value"]=>
            string(10) "test_value"
            ["compare"]=>
            string(4) "LIKE"
          }
        }
    }
    

    It should look like this:

    array(1) {
      ["meta_query"]=>
      array(2) {
        ["relation"]=>
        string(2) "OR"
        [0]=>
        array(3) {
          ["key"]=>
          string(4) "test"
          ["value"]=>
          string(10) "test_value"
          ["compare"]=>
          string(4) "LIKE"
        }
      }
    }
    

    The problem is the trailing square brackets here: $args['meta_query'][] That is incorrect. To combine your values do something like this instead:

    $meta_q = array();
    
    $key ='test';
    $value='test_value';
    
    if (!empty($key) && !empty($value)) {
      $meta_q[] = array(
        'key' => $key,
        'value' => $value,
        'compare' => 'LIKE'
      );
    }
    
    $key2 ='test';
    $value2='test_value';
    
    if (!empty($key2) && !empty($value2)) {
      $meta_q[] = array(
        'key' => $key2,
        'value' => $value2,
        'compare' => 'LIKE'
      );
    }
    
    $args = array(
      'relation' => 'OR',
      'meta_query' => $meta_q,
    );
    var_dump($args);
    

Comments are closed.