0
votes

I'm trying to run a WP_Query in order to search for all the products in my database with multiple meta values.

e.g

  • Product 1 -> meta_key['key1'] ->meta_value['value1']
  • Product 2 -> meta_key['key1'] ->meta_value['value2']
  • Product 3 -> meta_key['key1'] ->meta_value['value3']

So i want to get all three products.My arguments are

$args = array(
        'post_type' => 'product',
        'posts_per_page' => 2,
        'orderby'    => 'title',
        'order'      => 'ASC',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key'     => 'key1',
                'value'   => 'val1',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val2',
                'compare' => '='
            ),
            array(
                'key'     => 'key1',
                'value'   => 'val3',
                'compare' => '='
            ),
        ),
        'paged' => $paged
        );

The problem is that no products are returned. Instead , if a give only one meta_key => meta_value pair it works fine

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_key' => 'key1',
    'meta_value' =>'val1',
    'paged' => $paged
);
1

1 Answers

0
votes

You should use IN as compare value, like this:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => 2,
    'orderby'    => 'title',
    'order'      => 'ASC',
    'meta_query' => array(
        array(
            'key'     => 'key1',
            'value'   => array('val1','val2','val3'),
            'compare' => 'IN',
        ),
    ),
    'paged' => $paged
);

Hope it helps!