Search code examples
woocommercehook-woocommercecoupon

Get Coupon code applied to the product in woocommerce


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!


Solution

  • 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.