Query WooCommerce orders where meta data does not exist

I’m trying to fetch all my WooCommerce orders where some additional metadata is equal to not empty.

$orders = wc_get_orders( array(
    'orderby'   => 'date',
    'order'     => 'DESC',
    'meta_query' => array(
        array(
            'key' => 'var_rate',
            'compare' => 'NOT EXISTS',
        )
    )
));

So if the var_rate is empty or doesn’t exist then do not return that record. At the moment all orders are returned using those arguments.

Example of empty record –

object(WC_Meta_Data)#2344 (2) {
  ["current_data":protected]=>
  array(3) {
    ["id"]=>
    int(6471)
    ["key"]=>
    string(15) "var_rate"
    ["value"]=>
    NULL
  }
  ["data":protected]=>
  array(3) {
    ["id"]=>
    int(6471)
    ["key"]=>
    string(15) "var_rate"
    ["value"]=>
    NULL
  }
}

2 Answers
2

The meta_query argument (that you can use in a WP_Query) is not enabled by default when using a WC_Order_Query through wc_get_orders() WooCommerce function.

But for you can use the undocumented Custom Field Parameters (just like in a WP_Query):

  • meta_key
  • meta_value
  • meta_value_num
  • meta_compare

So in your case you can use the following instead:

$orders = wc_get_orders( array(
    'limit'        => -1, // Query all orders
    'orderby'      => 'date',
    'order'        => 'DESC',
    'meta_key'     => 'var_rate', // The postmeta key field
    'meta_compare' => 'NOT EXISTS', // The comparison argument
));

This time it works nicely (Tested on WooCommerce 3.5.8 and 3.6.2).

Leave a Comment