简体   繁体   English

将运输和优惠券添加到使用 wc_create_order() 创建的 WooCommerce 订单

[英]Add Shipping & Coupons to WooCommerce Order created with wc_create_order()

I have a custom API endpoint for creating orders, but the order I create don't have any shipping charges and I also want the option to be able to add coupon codes to them.我有一个用于创建订单的自定义 API 端点,但我创建的订单没有任何运费,我还希望该选项能够向它们添加优惠券代码。 Here's what I have so far:这是我到目前为止所拥有的:

  $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();

The order creates as expected but there are no shipping charges, and the coupon code gets applied but the discount from the coupon doesn't show up, the total price remains the same.订单按预期创建,但不收取运费,并且应用了优惠券代码但未显示优惠券的折扣,总价保持不变。 Any help would be appreciated!任何帮助,将不胜感激!

This worked for me, but be warned - I have only one shipping method available, and it's custom.这对我有用,但请注意 - 我只有一种运输方式可用,而且是自定义的。

// $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 );

You can pass additional attributes to WC_Shipping_Rate constructor, see https://docs.woocommerce.com/wc-apidocs/class-WC_Shipping_Rate.html您可以将其他属性传递给 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 );

All params are optional.所有参数都是可选的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM