3

Im trying to get orders in WooCommerce (ideally through wc_get_orders) where the coupon code "some_code" was used.

My try:

function get_orders_with_coupon($coupon){
    $customer_orders = wc_get_orders(array(
        'limit' => -1,
        'coupon' => $coupon
    ));
    return $customer_orders;
}

Only one code is used in Woo orders.

1
  • Hi, a very similar question was asked on Stackoverflow, see here. Consider checking out the answer to that question! Commented Mar 4, 2019 at 21:40

1 Answer 1

0

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:

  1. 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.
  2. 'limit': Set to -1 to retrieve all orders.
  3. '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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.