Reputation: 386
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. 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!
Upvotes: 2
Views: 2672
Reputation: 81
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
/**
* 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.
Upvotes: 2