在woocommerce中,我们可以使用优惠券功能(固定金额,百分比金额...)为任何订单添加折扣。
我尝试了以下代码:
function ocost_check_coupon(WP_REST_Request $request){
$coupon_code = $request->get_param('coupon');
$order_id = $request->get_param('order_id');
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
$order = wc_get_order($order_id);
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();
}
}
if ($order->save()) {
$results = array();
$results = array(
'status' => 'true',
'message' => 'done and apply coupon to order',
);
return $results;
} else{
return array(
'status' => 'error',
'message' => 'error to complete coupon function'
);
}
}
但是似乎没有应用任何优惠券。 我只是在订单中添加了代码:如果在wp-admin中找不到此优惠券,如何在应用优惠券之前进行检查?
任何帮助将不胜感激。