WC_Discounts::validate_coupon_excluded_product_ids │ protected │ WC 3.2.0

Exclude products.

Method of the class: WC_Discounts{}

Returns

bool.

Usage

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

Changelog

Since 3.2.0 Introduced.

WC_Discounts::validate_coupon_excluded_product_ids() code WC 11.1.2

protected function validate_coupon_excluded_product_ids( $coupon ) {
	// Exclude Products.
	if ( count( $coupon->get_excluded_product_ids() ) > 0 ) {
		$products = array();

		foreach ( $this->get_items_to_validate() as $item ) {
			if ( $item->product && in_array( $item->product->get_id(), $coupon->get_excluded_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_excluded_product_ids(), true ) ) {
				$products[] = $item->product->get_name();
			}
		}

		$valid = empty( $products );

		/**
		 * Filter whether the coupon is valid for the cart given its excluded_product_ids restriction.
		 *
		 * 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. When
		 * rejecting, use the woocommerce_coupon_error filter (error code
		 * WC_Coupon::E_WC_COUPON_EXCLUDED_PRODUCTS) to customize the message shown to the shopper.
		 *
		 * @since 11.1.0
		 * @param bool         $valid     Whether the coupon is valid given the excluded products.
		 * @param WC_Coupon    $coupon    Coupon data.
		 * @param WC_Discounts $discounts The discounts instance.
		 */
		$valid = apply_filters( 'woocommerce_coupon_is_valid_for_excluded_product_ids', $valid, $coupon, $this );

		if ( ! $valid ) {
			// When a filter forces rejection but no cart item matched, fall back to the generic message.
			throw new Exception(
				empty( $products )
					? sprintf(
						/* translators: %s: coupon code */
						esc_html__( 'Sorry, coupon "%s" is not applicable to selected products.', 'woocommerce' ),
						esc_html( $coupon->get_code() )
					)
					: sprintf(
						/* translators: %1$s: coupon code, %2$s: products list */
						esc_html__( 'Sorry, coupon "%1$s" is not applicable to the products: %2$s.', 'woocommerce' ),
						esc_html( $coupon->get_code() ),
						esc_html( implode( ', ', $products ) )
					),
				113
			);
		}
	}

	return true;
}