WC_Discounts::apply_coupon( WC_Coupon $coupon, bool $validate = true )
Apply a discount to all items using a coupon.
Description Description
Parameters Parameters
- $coupon
-
(Required) Coupon object being applied to the items.
- $validate
-
(Optional) Set to false to skip coupon validation.
Default value: true
Return Return
(bool|WP_Error) True if applied or WP_Error instance in failure.
Source Source
File: includes/class-wc-discounts.php
public function apply_coupon( $coupon, $validate = true ) {
if ( ! is_a( $coupon, 'WC_Coupon' ) ) {
return new WP_Error( 'invalid_coupon', __( 'Invalid coupon', 'woocommerce' ) );
}
$is_coupon_valid = $validate ? $this->is_coupon_valid( $coupon ) : true;
if ( is_wp_error( $is_coupon_valid ) ) {
return $is_coupon_valid;
}
if ( ! isset( $this->discounts[ $coupon->get_code() ] ) ) {
$this->discounts[ $coupon->get_code() ] = array_fill_keys( array_keys( $this->items ), 0 );
}
$items_to_apply = $this->get_items_to_apply_coupon( $coupon );
// Core discounts are handled here as of 3.2.
switch ( $coupon->get_discount_type() ) {
case 'percent':
$this->apply_coupon_percent( $coupon, $items_to_apply );
break;
case 'fixed_product':
$this->apply_coupon_fixed_product( $coupon, $items_to_apply );
break;
case 'fixed_cart':
$this->apply_coupon_fixed_cart( $coupon, $items_to_apply );
break;
default:
$this->apply_coupon_custom( $coupon, $items_to_apply );
break;
}
return true;
}
Changelog Changelog
| Version | Description |
|---|---|
| 3.2.0 | Introduced. |