WC_Discounts::validate_coupon_product_categories
Ensure coupon is valid for product categories in the list is valid or throw exception.
Method of the class: WC_Discounts{}
No Hooks.
Returns
true|false.
Usage
// protected - for code of main (parent) or child class $result = $this->validate_coupon_product_categories( $coupon );
- $coupon(WC_Coupon) (required)
- Coupon data.
Changelog
| Since 3.2.0 | Introduced. |
WC_Discounts::validate_coupon_product_categories() WC Discounts::validate coupon product categories code WC 10.6.2
protected function validate_coupon_product_categories( $coupon ) {
if ( count( $coupon->get_product_categories() ) > 0 ) {
$valid = false;
foreach ( $this->get_items_to_validate() as $item ) {
if ( $coupon->get_exclude_sale_items() && $item->product && $item->product->is_on_sale() ) {
continue;
}
$product_cats = wc_get_product_cat_ids( $item->product->get_id() );
if ( $item->product->get_parent_id() ) {
$product_cats = array_merge( $product_cats, wc_get_product_cat_ids( $item->product->get_parent_id() ) );
}
// If we find an item with a cat in our allowed cat list, the coupon is valid.
if ( count( array_intersect( $product_cats, $coupon->get_product_categories() ) ) > 0 ) {
$valid = true;
break;
}
}
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;
}