1

I am trying to retrieve the shop coupon code applied to a particular product. I used the below code but it did not work.

$WC_Cart = new WC_Cart();
$var = $WC_Cart->get_applied_coupons();

Can anyone please help me to get the solution. Thanks in advance!

Praveen
  • 985
  • 8
  • 31
  • Can you tell where you need to retrieve and show the applied coupon? It seems like you just want to get report for a product-coupon relationship but Im not sure. – MrEbabi Jul 29 '19 at 11:01
  • I want to display the coupon in orders page – Praveen Jul 29 '19 at 11:02

1 Answers1

2

I think this will solve your problem. I tested the code and it worked as:

  1. echo order no
  2. echo used coupons for this order no
  3. run step 1 and step 2 for all orders

You may need to modify it.

//function to get orders - completed, pending and processing
function lets_get_all_orders()
{
    $customer_orders = wc_get_orders( array(
    'limit'    => -1,
    'status'   => array('completed','pending','processing')
    ) );
    return $customer_orders;
}

//function to get all used coupons in the orders
function lets_get_all_used()
{
    $orders = lets_get_all_orders();

    //traverse all users and echo coupon codes
    foreach($orders as $order)
    {
        $order_discount = $order->discount_total;
        $order_used_coupons = $order->get_used_coupons();
        $order_id = $order->ID;

        //check if any coupon is used in this order
        if($order_discount>0) 
        {
            echo "Order No: $order_id <br> Used Coupons:";
            //display coupon code(s)
            foreach($order_used_coupons as $order_used_coupon)
            {
                echo " - $order_used_coupon";
                echo "<br>";
            }
        }
    }
}

Please inform me if you need any help. Have a good day.

MrEbabi
  • 740
  • 5
  • 16