且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以编程方式将优惠券应用于 WooCommerce3 中的订单

更新时间:2023-11-30 12:58:40

好的,所以我玩了一段时间,看起来在 V3 中的东西更手动一些.

OK, so I played about a little longer and it looks like in V3 things are a little more manual.

WC_Order_Item_Coupon 项目添加到 woo 订单即可.它将优惠券对象添加到订单对象.不进行计算,产品线项目保持不变.您必须手动迭代产品项目并通过计算行项目总计和小计自己应用优惠券.calculate_totals() 然后按预期执行.

Adding a WC_Order_Item_Coupon item to a woo order does simply that. It adds the coupon object to the order object. No calculations are made and the product line items remain unchanged. You have to iterate over the product items manually and apply the coupon yourself by calculating the line item totals and subtotals. calculate_totals() then does as expected.

// Create the coupon
global $woocommerce;
$coupon = new WC_Coupon($coupon_code);

// Get the coupon discount amount (My coupon is a fixed value off)
$discount_total = $coupon->get_amount();

// Loop through products and apply the coupon discount
foreach($order->get_items() as $order_item){
    $product_id = $order_item->get_product_id();

    if($this->coupon_applies_to_product($coupon, $product_id)){
        $total = $order_item->get_total();
        $order_item->set_subtotal($total);
        $order_item->set_total($total - $discount_total);
        $order_item->save();
    }
}
$order->save();

我编写了一个辅助函数来确保优惠券适用于相关产品coupon_applies_to_product().鉴于我完全在代码中创建订单,绝对不需要......但我在其他地方使用它所以添加了它.

I wrote a helper function to make sure the coupon applies to the product in question coupon_applies_to_product(). Strictly not needed given I'm creating the order entirely in code.. but I use it it other places so added it.

// Add the coupon to the order
$item = new WC_Order_Item_Coupon();
$item->set_props(array('code' => $coupon_code, 'discount' => $discount_total, 'discount_tax' => 0));
$order->add_item($item);
$order->save();

您现在可以在 wp-admin 中获得格式良好的订单,其中包含显示特定折扣 + 优惠券代码等的订单项.

You now get the nicely formatted order in wp-admin with line items showing the specific discount + the coupon code etc.