WordPress at Your Fingertips
function is not described

WC_Discounts::apply_coupon() public WC 3.2.0

Apply a discount to all items using a coupon.

{} It's a method of the class: WC_Discounts{}

No Hooks.

Return

true|false|WP_Error. True if applied or WP_Error instance in failure.

Usage

$WC_Discounts = new WC_Discounts();
$WC_Discounts->apply_coupon( $coupon, $validate );
$coupon(WC_Coupon) (required)
Coupon object being applied to the items.
$validate(true|false)
Set to false to skip coupon validation.
Default: true

Changelog

Since 3.2.0 Introduced.

Code of WC_Discounts::apply_coupon() WC 5.7.1

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;
}