WC_API_Orders::set_fee()protectedWC 2.2

Create or update an order fee

Method of the class: WC_API_Orders{}

No Hooks.

Return

null. Nothing (null).

Usage

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

Changelog

Since 2.2 Introduced.

WC_API_Orders::set_fee() code WC 8.7.0

protected function set_fee( $order, $fee, $action ) {

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

		// fee title is required
		if ( ! isset( $fee['title'] ) ) {
			throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee title is required', 'woocommerce' ), 400 );
		}

		$item = new WC_Order_Item_Fee();
		$item->set_order_id( $order->get_id() );
		$item->set_name( wc_clean( $fee['title'] ) );
		$item->set_total( isset( $fee['total'] ) ? floatval( $fee['total'] ) : 0 );

		// if taxable, tax class and total are required
		if ( ! empty( $fee['taxable'] ) ) {
			if ( ! isset( $fee['tax_class'] ) ) {
				throw new WC_API_Exception( 'woocommerce_invalid_fee_item', __( 'Fee tax class is required when fee is taxable.', 'woocommerce' ), 400 );
			}

			$item->set_tax_status( 'taxable' );
			$item->set_tax_class( $fee['tax_class'] );

			if ( isset( $fee['total_tax'] ) ) {
				$item->set_total_tax( isset( $fee['total_tax'] ) ? wc_format_refund_total( $fee['total_tax'] ) : 0 );
			}

			if ( isset( $fee['tax_data'] ) ) {
				$item->set_total_tax( wc_format_refund_total( array_sum( $fee['tax_data'] ) ) );
				$item->set_taxes( array_map( 'wc_format_refund_total', $fee['tax_data'] ) );
			}
		}

		$order->add_item( $item );
	} else {

		$item = new WC_Order_Item_Fee( $fee['id'] );

		if ( isset( $fee['title'] ) ) {
			$item->set_name( wc_clean( $fee['title'] ) );
		}

		if ( isset( $fee['tax_class'] ) ) {
			$item->set_tax_class( $fee['tax_class'] );
		}

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

		if ( isset( $fee['total_tax'] ) ) {
			$item->set_total_tax( floatval( $fee['total_tax'] ) );
		}

		$fee_id = $item->save();

		if ( ! $fee_id ) {
			throw new WC_API_Exception( 'woocommerce_cannot_update_fee', __( 'Cannot update fee, try again.', 'woocommerce' ), 500 );
		}
	}
}