wc_get_products with two meta_query condition being ignored

1.8k views Asked by At

I'm tryng to do a wc_get_products with two meta_query conditions, but it doesn't work. It returns random results and I don't know why (When I refresh the page the products given change)

The code that I'm using is:

$args = array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => $itemsperpage,
            'paged' => $paged,
            'meta_query' => array(
            'relation' => 'AND',
            array(
                'relation'  => 'AND',
                    array(
                    'key' => '_iop',
                    'value' => '2',
                    'compare' => '=',
                    ),
                ),
            array(
                'relation' => 'AND',
                    array(
                    'key' => '_iop',
                    'value' => '6',
                    'compare' => '=',
                    ),
                ),
            ),
            'orderby'     => 'menu_order',
            'order'     => 'ASC'
        ); 

$products = wc_get_products($args);

I want to show results which meta key _iop is 2 or 6, but doesn't work. ¿Where is the problem?

Thanks!

1

There are 1 answers

0
disinfor On

You have a couple issues with this query:

  1. There is no inner relation for the inner array of the meta_query.
  2. You don't need both inner arrays, since it can be a single array for your value.
  3. You don't need your outer 'relation' => 'AND', since it's now a single inner array.
  4. wc_get_products does not accept the normal query args - so you will need to use get_posts or create a new WP_Query( $args ).

If you must use the wc_get_products, check this out: WC_get_products Meta Query being ignored

$args = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => $itemsperpage,
    'paged' => $paged,
    'meta_query' => array (
        array(
            'key' => '_iop',
            'value' => array(2,6),
            'compare' => '=',
        ),
    ),
    'orderby'     => 'menu_order',
    'order'     => 'ASC'
);

$products = new WP_Query($args);