2015-10-02 61 views
0

无法获得优惠券以将折扣应用于订单。 (以编程方式创建一个新的订单)Woocommerce - 使用wc_create_order创建新订单,但折扣不起作用

下面的代码:

$order = wc_create_order(); 
$order->add_product(get_product($pid), $item['quantity']); // pid 8 & qty 1 
$order->set_address($address_billing, 'billing'); 
$order->set_address($address_shipping, 'shipping'); 
$order->add_coupon($discount['code'], ($discount['amount']/100)); // not pennies (use dollars amount) 
$order->set_total(($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount) 
$order->set_payment_method($this); 
$rate = new WC_Shipping_Rate( $response_body['shippingMethodCode'] , $ship_method_title, ($response_body['shippingCost']/100), array(), $response_body['shippingMethodCode']); 
$order->add_shipping($rate); 
$order->calculate_totals(); 
$return_url = $this->get_return_url($order); 

顺序在Woocommerce创建和一切看起来不错,除了被应用于并不反映在返回URL感谢折扣金额的优惠券代码您查看Woocommerce订单时 - 不在wp-admin中 - 并且 - 不在发送出去的新客户订单电子邮件中。...

它确实在wp-admin中显示优惠券代码,但折扣行仍然显示$ 0,总额不显示任何减去的金额。

任何人都知道在这里做错了什么?现在已经有几个星期了,似乎无法解决。

回答

4

要达到这个目标,您需要计算您以编程方式添加到订单中的每件产品的折扣,并将其作为附加参数传递给订单。查看更新示例:

$order = wc_create_order(); 
$product_to_add = get_product($pid); 
$sale_price = $product_to_add->get_price(); 

// Here we calculate the final price with the discount 
$final_price = round($sale_price * ((100-$discount['amount'])/100), 2); 
// Create the price params that will be passed with add_product(), if you have taxes you will need to calculate them here too 
$price_params = array('totals' => array('subtotal' => $sale_price, 'total' => $final_price)); 

$order->add_product(get_product($pid), $item['quantity'], $price_params); // pid 8 & qty 1 
$order->set_address($address_billing, 'billing'); 
$order->set_address($address_shipping, 'shipping'); 
$order->add_coupon($discount['code'], ($discount['amount']/100)); // not pennies (use dollars amount) 
$order->set_total(($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount) 
$order->set_payment_method($this); 
$rate = new WC_Shipping_Rate( $response_body['shippingMethodCode'] , $ship_method_title, ($response_body['shippingCost']/100), array(), $response_body['shippingMethodCode']); 
$order->add_shipping($rate);enter code here 
$order->calculate_totals(); 
$return_url = $this->get_return_url($order); 
+0

谢谢。它工作完美。 – Dudling

+0

你已经救了我的生命,自从优惠券未正确应用以来,我一直在处理这个问题2天。谢谢!! –