6

I'm trying to write a function that retrieves a list of WooCommerce orders which use a specified coupon code and are in a specified date range, then sums the total discounts applied to those orders.

After a little googling I feel like I should be using something like

$customer_orders = get_posts( array(
    'numberposts' => -1,
    'meta_key'    => ???,
    'meta_value'  => $CouponToSearchFor,
    'post_type'   => wc_get_order_types(),
    'post_status' => array_keys( wc_get_order_statuses() ),
) ); 

I've tried:

'meta_key' => 'coupon'
'meta_key' => 'shop_coupon'
'meta_key' => '_coupon'

But none of those work. How can I find out which meta_key/meta_value terms will give me what I need?

Additionally I think meta_query can be used to perform the date filtering as part of this get_posts() query, is that correct?

Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
capsid
  • 135
  • 1
  • 11

1 Answers1

16

Your code is not working because by default WooCommerce does't store used coupon code in wp_postmeta table. It stores in wp_woocommerce_order_items table, under order_item_type => coupon and order_item_name => YOUR_CODE.

You have to first get all the Order ID(s), then you have to loop it to get the desired total, or tax or discount.

Here is the code:

function wh_getOrderbyCouponCode($coupon_code, $start_date, $end_date) {
    global $wpdb;
    $return_array = [];
    $total_discount = 0;

    $query = "SELECT
        p.ID AS order_id
        FROM
        {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
        WHERE
        p.post_type = 'shop_order' AND
        p.post_status IN ('" . implode("','", array_keys(wc_get_order_statuses())) . "') AND
        woi.order_item_type = 'coupon' AND
        woi.order_item_name = '" . $coupon_code . "' AND
        DATE(p.post_date) BETWEEN '" . $start_date . "' AND '" . $end_date . "';";

    $orders = $wpdb->get_results($query);

    if (!empty($orders)) {
        $dp = ( isset($filter['dp']) ? intval($filter['dp']) : 2 );
        //looping throught all the order_id
        foreach ($orders as $key => $order) {
            $order_id = $order->order_id;
            //getting order object
            $objOrder = wc_get_order($order_id);

            $return_array[$key]['order_id'] = $order_id;
            $return_array[$key]['total'] = wc_format_decimal($objOrder->get_total(), $dp);
            $return_array[$key]['total_discount'] = wc_format_decimal($objOrder->get_total_discount(), $dp);
            $total_discount += $return_array[$key]['total_discount'];
        }
//        echo '<pre>';
//        print_r($return_array);
    }
    $return_array['full_discount'] = $total_discount;
    return $return_array;
}

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

USAGE

$orders = wh_getOrderbyCouponCode('my_code', '2016-09-17', '2016-10-07');
echo 'Total Discount : ' . $orders['full_discount'];
//print_r($orders);

Please Note:

All dates are in YYYY-MM-DD format.
print_r(array_keys(wc_get_order_statuses())); will output something like this:

Array
(
    [0] => wc-pending
    [1] => wc-processing
    [4] => wc-on-hold
    [5] => wc-completed
    [6] => wc-cancelled
    [7] => wc-refunded
    [8] => wc-failed
)

Code is tested and works.

Hope this helps!

Raunak Gupta
  • 10,412
  • 3
  • 58
  • 97
  • Thank you so much for the explanation. It is very thorough. I've hooked up the function inside my utility plugin but when I print $orders after the query it is an empty Array(). I double checked the coupon code and date range to make sure an order exists for this input. And I printed $query and everything looked correct in there. I'm new to PHP and Wordpress development but your code makes sense so I'm wondering if I'm doing something wrong? – capsid Mar 13 '17 at 20:08
  • I can select the coupons using parts of your query inside phpMyAdmin so I know they are there. I also double checked to make sure the prefix was correct. When I run the entire printed query inside phpMyAdmin I get the same empty set. Thanks for your thoughts. – capsid Mar 13 '17 at 20:10
  • I can select the orders correctly in phpMyAdmin all the way up to the part `AND DATE(p.post_date) BETWEEN '11/01/2016' AND '12/31/2016'` When I add that bit in the orders no longer select correctly even though I manually verified the dates of the applicable orders. – capsid Mar 13 '17 at 20:15
  • Ok, I think I am not providing the dates to the function in the correct format of YYYY-MM-DD. I will fix that and then check back. Thank you! – capsid Mar 13 '17 at 20:25
  • 1
    That was it! All I needed to do to my dates before passing them to your function was: `$d1 = date('Y-m-d', strtotime($start_date));` Thanks again :) – capsid Mar 13 '17 at 20:41
  • I wan't online at that time so could't respond to your comment, but yes I know that order status and date can cause any issue, so I have pointed out that in my _Note_. Anyway I'm glad this helps you, moreover this question 'll help community also. – Raunak Gupta Mar 14 '17 at 10:04