WC_Discounts::validate_coupon_excluded_items │ protected │ WC 3.2.0

All exclusion rules must pass at the same time for a product coupon to be valid.

Method of the class: WC_Discounts{}

Returns

bool.

Usage

// protected - for code of main (parent) or child class
$result = $this->validate_coupon_excluded_items( $coupon );
$coupon(WC_Coupon) (required)
Coupon data.

Changelog

Since 3.2.0 Introduced.

WC_Discounts::validate_coupon_excluded_items() code WC 11.1.2

protected function validate_coupon_excluded_items( $coupon ) {
	$items = $this->get_items_to_validate();
	if ( ! empty( $items ) && $coupon->is_type( wc_get_product_coupon_types() ) ) {
		$valid = false;

		foreach ( $items as $item ) {
			if ( $item->product && $coupon->is_valid_for_product( $item->product, $item->object ) ) {
				$valid = true;
				break;
			}
		}

		/**
		 * Filter whether the coupon is valid for the cart given its excluded items.
		 *
		 * Return true to treat the coupon as valid, or false to reject it. Mind the polarity: these
		 * woocommerce_coupon_is_valid_for_* filters follow the woocommerce_coupon_is_valid convention where
		 * true means valid. This is the opposite of the woocommerce_coupon_validate_* filters
		 * (e.g. woocommerce_coupon_validate_expiry_date), where returning true rejects the coupon.
		 *
		 * @since 11.1.0
		 * @param bool         $valid     Whether the coupon is valid given the cart's exclusion rules.
		 * @param WC_Coupon    $coupon    Coupon data.
		 * @param WC_Discounts $discounts The discounts instance.
		 */
		$valid = apply_filters( 'woocommerce_coupon_is_valid_for_excluded_items', $valid, $coupon, $this );

		if ( ! $valid ) {
			throw new Exception(
				sprintf(
					/* translators: %s: coupon code */
					esc_html__( 'Sorry, coupon "%s" is not applicable to selected products.', 'woocommerce' ),
					esc_html( $coupon->get_code() )
				),
				109
			);
		}
	}

	return true;
}