WC_Abstract_Order::apply_coupon( string|WC_Coupon $raw_coupon )
Apply a coupon to the order and recalculate totals.
Description Description
Parameters Parameters
- $raw_coupon
-
(Required) Coupon code or object.
Return Return
(true|WP_Error) True if applied, error if not.
Source Source
File: includes/abstracts/abstract-wc-order.php
public function apply_coupon( $raw_coupon ) {
if ( is_a( $raw_coupon, 'WC_Coupon' ) ) {
$coupon = $raw_coupon;
} elseif ( is_string( $raw_coupon ) ) {
$code = wc_format_coupon_code( $raw_coupon );
$coupon = new WC_Coupon( $code );
if ( $coupon->get_code() !== $code ) {
return new WP_Error( 'invalid_coupon', __( 'Invalid coupon code', 'woocommerce' ) );
}
} else {
return new WP_Error( 'invalid_coupon', __( 'Invalid coupon', 'woocommerce' ) );
}
// Check to make sure coupon is not already applied.
$applied_coupons = $this->get_items( 'coupon' );
foreach ( $applied_coupons as $applied_coupon ) {
if ( $applied_coupon->get_code() === $coupon->get_code() ) {
return new WP_Error( 'invalid_coupon', __( 'Coupon code already applied!', 'woocommerce' ) );
}
}
$discounts = new WC_Discounts( $this );
$applied = $discounts->apply_coupon( $coupon );
if ( is_wp_error( $applied ) ) {
return $applied;
}
$data_store = $coupon->get_data_store();
// Check specific for guest checkouts here as well since WC_Cart handles that seperately in check_customer_coupons.
if ( $data_store && 0 === $this->get_customer_id() ) {
$usage_count = $data_store->get_usage_by_email( $coupon, $this->get_billing_email() );
if ( 0 < $coupon->get_usage_limit_per_user() && $usage_count >= $coupon->get_usage_limit_per_user() ) {
return new WP_Error(
'invalid_coupon',
$coupon->get_coupon_error( 106 ),
array(
'status' => 400,
)
);
}
}
$this->set_coupon_discount_amounts( $discounts );
$this->save();
// Recalculate totals and taxes.
$this->recalculate_coupons();
// Record usage so counts and validation is correct.
$used_by = $this->get_user_id();
if ( ! $used_by ) {
$used_by = $this->get_billing_email();
}
$coupon->increase_usage_count( $used_by );
return true;
}
Changelog Changelog
| Version | Description |
|---|---|
| 3.2.0 | Introduced. |