WordPress at Your Fingertips
function is not described

WC_API_Orders::set_shipping() protected WC 2.2

Create or update an order shipping method

{} It's a method of the class: WC_API_Orders{}

No Hooks.

Return

null. Nothing.

Usage

// protected - for code of main (parent) or child class
$result = $this->set_shipping( $order, $shipping, $action );
$order(\WC_Order) (required)
-
$shipping(array) (required)
item data
$action(string) (required)
'create' to add shipping or 'update' to update it

Changelog

Since 2.2 Introduced.

Code of WC_API_Orders::set_shipping() WC 5.7.1

protected function set_shipping( $order, $shipping, $action ) {

	// total must be a positive float
	if ( isset( $shipping['total'] ) && floatval( $shipping['total'] ) < 0 ) {
		throw new WC_API_Exception( 'woocommerce_invalid_shipping_total', __( 'Shipping total must be a positive amount.', 'woocommerce' ), 400 );
	}

	if ( 'create' === $action ) {

		// method ID is required
		if ( ! isset( $shipping['method_id'] ) ) {
			throw new WC_API_Exception( 'woocommerce_invalid_shipping_item', __( 'Shipping method ID is required.', 'woocommerce' ), 400 );
		}

		$rate = new WC_Shipping_Rate( $shipping['method_id'], isset( $shipping['method_title'] ) ? $shipping['method_title'] : '', isset( $shipping['total'] ) ? floatval( $shipping['total'] ) : 0, array(), $shipping['method_id'] );
		$item = new WC_Order_Item_Shipping();
		$item->set_order_id( $order->get_id() );
		$item->set_shipping_rate( $rate );
		$order->add_item( $item );
	} else {

		$item = new WC_Order_Item_Shipping( $shipping['id'] );

		if ( isset( $shipping['method_id'] ) ) {
			$item->set_method_id( $shipping['method_id'] );
		}

		if ( isset( $shipping['method_title'] ) ) {
			$item->set_method_title( $shipping['method_title'] );
		}

		if ( isset( $shipping['total'] ) ) {
			$item->set_total( floatval( $shipping['total'] ) );
		}

		$shipping_id = $item->save();

		if ( ! $shipping_id ) {
			throw new WC_API_Exception( 'woocommerce_cannot_update_shipping', __( 'Cannot update shipping method, try again.', 'woocommerce' ), 500 );
		}
	}
}