I'm trying to get all the shop orders with a meta key "order_referrer_id" and the value will be a user id for example "1060".
This is what i have tried so far:
$args = array(
'limit' => -1,
'status' => 'completed',
'meta_query' => array(
array(
'key' => 'order_referrer_id',
'value' => 1060,
'compare' => '='
),
),
'return' => 'ids',
);
$orders = wc_get_orders( $args );
For some reason the query ignore the meta query and returns all the orders.
What is the correct way to filter shop orders?
CodePudding user response:
wc_get_orders
and WC_Order_Query
provide a standard way of retrieving orders that is safe to use and will not break due to database changes in future WooCommerce versions.
Source: wc_get_orders and WC_Order_Query
You can use meta_key
, meta_value
and meta_compare
, so you get:
$args = array(
'status' => 'completed', // Accepts a string: one of 'pending', 'processing', 'on-hold', 'completed', 'refunded, 'failed', 'cancelled', or a custom order status.
'meta_key' => 'order_referrer_id', // Postmeta key field
'meta_value' => 1060, // Postmeta value field
'meta_compare' => '=', // Possible values are ‘=’, ‘!=’, ‘>’, ‘>=’, ‘<‘, ‘<=’, ‘LIKE’, ‘NOT LIKE’, ‘IN’, ‘NOT IN’, ‘BETWEEN’, ‘NOT BETWEEN’, ‘EXISTS’ (only in WP >= 3.5), and ‘NOT EXISTS’ (also only in WP >= 3.5). Values ‘REGEXP’, ‘NOT REGEXP’ and ‘RLIKE’ were added in WordPress 3.7. Default value is ‘=’.
'return' => 'ids' // Accepts a string: 'ids' or 'objects'. Default: 'objects'.
);
$orders = wc_get_orders( $args );
// NOT empty
if ( ! empty ( $orders ) ) {
foreach ( $orders as $order ) {
echo '<p>ID = ' . $order . '</p>';
}
}