首页 > 解决方案 > 在woocommerce中获取应用于产品的优惠券代码

问题描述

我正在尝试检索应用于特定产品的商店优惠券代码。我使用了下面的代码,但它不起作用。

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

谁能帮我找到解决方案。提前致谢!

标签: woocommercehook-woocommercecoupon

解决方案


我认为这将解决您的问题。我测试了代码,它的工作原理是:

  1. 回声订单号
  2. 回显此订单使用的优惠券 否
  3. 对所有订单运行第 1 步和第 2 步

您可能需要对其进行修改。

//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>";
            }
        }
    }
}

如果您需要任何帮助,请通知我。祝你有美好的一天。


推荐阅读