WC_API_Orders::set_fee( WC_Order $order, array $fee, string $action )
Create or update an order fee
Description Description
Parameters Parameters
- $order
-
(Required)
- $fee
-
(Required) item data
- $action
-
(Required) 'create' to add fee or 'update' to update it
Source Source
File: includes/legacy/api/v2/class-wc-api-orders.php
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 );
}
}
}
Changelog Changelog
| Version | Description |
|---|---|
| 2.2 | Introduced. |