WC_API_Orders::set_coupon( WC_Order $order, array $coupon, string $action )

Create or update an order coupon


Description Description


Parameters Parameters

$order

(Required)

$coupon

(Required) item data

$action

(Required) 'create' to add coupon or 'update' to update it


Top ↑

Source Source

File: includes/legacy/api/v2/class-wc-api-orders.php

1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
protected function set_coupon( $order, $coupon, $action ) {
 
    // coupon amount must be positive float
    if ( isset( $coupon['amount'] ) && floatval( $coupon['amount'] ) < 0 ) {
        throw new WC_API_Exception( 'woocommerce_invalid_coupon_total', __( 'Coupon discount total must be a positive amount.', 'woocommerce' ), 400 );
    }
 
    if ( 'create' === $action ) {
 
        // coupon code is required
        if ( empty( $coupon['code'] ) ) {
            throw new WC_API_Exception( 'woocommerce_invalid_coupon_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
        }
 
        $item = new WC_Order_Item_Coupon();
        $item->set_props( array(
            'code'         => $coupon['code'],
            'discount'     => isset( $coupon['amount'] ) ? floatval( $coupon['amount'] ) : 0,
            'discount_tax' => 0,
            'order_id'     => $order->get_id(),
        ) );
        $order->add_item( $item );
    } else {
 
        $item = new WC_Order_Item_Coupon( $coupon['id'] );
 
        if ( isset( $coupon['code'] ) ) {
            $item->set_code( $coupon['code'] );
        }
 
        if ( isset( $coupon['amount'] ) ) {
            $item->set_discount( floatval( $coupon['amount'] ) );
        }
 
        $coupon_id = $item->save();
 
        if ( ! $coupon_id ) {
            throw new WC_API_Exception( 'woocommerce_cannot_update_order_coupon', __( 'Cannot update coupon, try again.', 'woocommerce' ), 500 );
        }
    }
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.2 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.