Skip to content
Advertisement

wc_order_query with meta_query not working when using relation

I am trying to use WC_Order_Query, to get all orders where a custom meta_key doesn’t exist, is empty or equal to 0

I’ve tried like a lot of the stuff documented on this site, but nothing seems to work. It just returns all content, which is the opposite of what i’m trying to do.

This is what most people have recommended so far, but it doesn’t seem to work as intended or maybe I am not seeing the issue here

    $args = array(
        'limit'     => 9999,
        'return'    => 'ids',
        'orderby'   => 'date',
        'order'     => 'DESC',
        'status'    => 'processing',
        'date_created' => '>='.$startdate,
        'meta_query'    => array(
            array(
                'relation' => 'OR',
                array(
                    'key'   => 'order_printed',
                    'compare' => 'NOT EXISTS'
                ),
                array(
                    'key'   => 'order_printed',
                    'compare' => '=',
                    'value' => ''
                ),
                array(
                    'key'   => 'order_printed',
                    'compare' => '=',
                    'value' => 0
                )
            )
            
        )
    );
    $query = new WC_Order_Query( $args );
    $orders = $query->get_orders();

Advertisement

Answer

This ended up being the solution:

    $args = array(
        'post_type'         => 'shop_order',
        'posts_per_page'    => -1,
        'post_status'       => 'any',
        'orderby'           => 'the_date',
        'order'             => 'DESC',
        'date_query'        => array(
            array(
                'after'     => $startdate . $starttime,
                'inclusive' => true
            )
        ),
        'meta_query'        => array(
            array(
                'relation'  => 'OR',
                array(
                    'key'       => 'order_printed',
                    'compare'   => 'NOT EXISTS'
                ),
                array(
                    'key'       => 'order_printed',
                    'compare'   => '=',
                    'value'     => ''
                ),
                array(
                    'key'       => 'order_printed',
                    'compare'   => '=',
                    'value'     => 0
                )
            )
            
        )
    );
    $query = new WP_Query( $args );
    $query_posts = $query->get_posts();

Thanks a lot to Boris for the assistance.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement