我有一个用于创建订单的自定义API端点,但我创建的订单没有任何运费,我还希望该选项能够为他们添加优惠券代码。这是我到目前为止所做的:
$address = array(
'first_name' => $payload['customer']['firstName'],
'last_name' => $payload['customer']['lastName'],
'email' => $payload['customer']['email'],
'phone' => $payload['customer']['phone'],
'address_1' => $payload['customer']['line1'],
'address_2' => $payload['customer']['line2'],
'city' => $payload['customer']['city'],
'state' => $payload['customer']['state'],
'postcode' => $payload['customer']['zip'],
'country' => 'US'
);
$order = wc_create_order();
foreach ($payload['items'] as $item) {
$order->add_product( get_product_by_sku( $item['sku'] ), $item['qty'] );
}
$order->set_address( $address, 'billing' );
$order->set_address( $address, 'shipping' );
$order->add_coupon( sanitize_text_field( 'couponcode' ));
$order->update_status('processing');
$order->calculate_shipping();
$order->calculate_totals();
订单按预期创建,但没有运费,优惠券代码已应用,但优惠券的折扣未显示,总价格保持不变。任何帮助将不胜感激!
答案 0 :(得分:2)
这对我有用,但要注意 - 我只提供一种送货方式,而且是定制的。
// $shipping_methods = WC()->shipping() ? WC()->shipping->load_shipping_methods() : array();
$shipping = new WC_Shipping_Rate();
$order->add_shipping( $shipping );
// $item_id = $order->add_shipping( $shipping );
您可以将其他属性传递给WC_Shipping_Rate构造函数,请参阅https://docs.woocommerce.com/wc-apidocs/class-WC_Shipping_Rate.html
/**
* Constructor.
*
* @param string $id
* @param string $label
* @param integer $cost
* @param array $taxes
* @param string $method_id
*/
$shipping = new WC_Shipping_Rate( $id, $label, $cost, $taxes, $method_id );
所有参数都是可选的。