WC_Coupon::is_valid_for_product()publicWC 1.0

Check if a coupon is valid for a product.

Method of the class: WC_Coupon{}

Return

true|false.

Usage

$WC_Coupon = new WC_Coupon();
$WC_Coupon->is_valid_for_product( $product, $values );
$product(WC_Product) (required)
Product instance.
$values(array)
Values.
Default: array()

WC_Coupon::is_valid_for_product() code WC 9.4.2

public function is_valid_for_product( $product, $values = array() ) {
	if ( ! $this->is_type( wc_get_product_coupon_types() ) || ! is_a( $product, WC_Product::class ) ) {
		return apply_filters( 'woocommerce_coupon_is_valid_for_product', false, $product, $this, $values );
	}

	$valid        = false;
	$product_cats = wc_get_product_cat_ids( $product->is_type( 'variation' ) ? $product->get_parent_id() : $product->get_id() );
	$product_ids  = array( $product->get_id(), $product->get_parent_id() );

	// Specific products get the discount.
	if ( count( $this->get_product_ids() ) && count( array_intersect( $product_ids, $this->get_product_ids() ) ) ) {
		$valid = true;
	}

	// Category discounts.
	if ( count( $this->get_product_categories() ) && count( array_intersect( $product_cats, $this->get_product_categories() ) ) ) {
		$valid = true;
	}

	// No product ids - all items discounted.
	if ( ! count( $this->get_product_ids() ) && ! count( $this->get_product_categories() ) ) {
		$valid = true;
	}

	// Specific product IDs excluded from the discount.
	if ( count( $this->get_excluded_product_ids() ) && count( array_intersect( $product_ids, $this->get_excluded_product_ids() ) ) ) {
		$valid = false;
	}

	// Specific categories excluded from the discount.
	if ( count( $this->get_excluded_product_categories() ) && count( array_intersect( $product_cats, $this->get_excluded_product_categories() ) ) ) {
		$valid = false;
	}

	// Sale Items excluded from discount.
	if ( $this->get_exclude_sale_items() && $product->is_on_sale() ) {
		$valid = false;
	}

	return apply_filters( 'woocommerce_coupon_is_valid_for_product', $valid, $product, $this, $values );
}