To retrieve orders that have used a specific coupon code in WooCommerce, your approach using wc_get_orders()
is on the right track. However, the coupon
argument is not a valid parameter for the wc_get_orders()
function. Instead, you'll need to use a custom query to filter orders based on the coupons used.
You can achieve this by querying the orders and checking the usage of the coupon within the meta data. Here's an updated version of your function that properly filters orders using a coupon code:
function get_orders_with_coupon($coupon) {
// Define query arguments
$args = array(
'limit' => -1,
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'used_coupons',
'value' => '"' . $coupon . '"', // Searching for the coupon in used_coupons serialized array
'compare' => 'LIKE'
)
)
);
// Get orders using wc_get_orders
$customer_orders = wc_get_orders($args);
return $customer_orders;
}
Explanation:
- Meta Query: Since WooCommerce stores used coupons as a serialized array in the order metadata under the key
used_coupons
, this query checks for the presence of the specified coupon code in this array.
- 'limit': Set to
-1
to retrieve all orders.
- 'orderby' and 'order': Optional parameters to sort orders by date in descending order.
Usage:
You can call this function by passing the specific coupon code you want to search for:
$coupon_code = "some_code"; // The coupon code you are looking for
$orders_with_coupon = get_orders_with_coupon($coupon_code);
// If you want to do something with the retrieved orders
foreach ($orders_with_coupon as $order) {
// Actions with the order
echo 'Order ID: ' . $order->get_id() . '<br>';
}
Make sure that this function is hooked into an appropriate action or called in a valid context in your WooCommerce setup to get the desired results.