1
votes

I need to prevent coupons being used if customer have any specific product variations in their cart with following attribute terms:

  • attribute_pa_style => swirly
  • attribute_pa_style => circle

I've looked through the Woocommerce scripts that apply to restricting specific products and specific categories, but can't figure it out with regard to attributes and all coupons.

Any help is appreciated.

1
Is "Style" product attribute used for product variations or not? What product types are you targeting?LoicTheAztec
Yes, style attribute is used for variations. The product is a variable product with two attributes used for variations "Color" and "Style" . I want to target any products that have the style attribute to be excluded from coupons.PurpleMonkeyDishwasher
How do I update this code if I want to reject coupons if only one of the "Style" attributes is selected? I've since changed this to "Style" - yes or no (the terms). I want to reject coupons if the product has the variation "yes" selected for the "style" attribute only. I tried removing the array but couldn't figure it out. Thanks very much for your help.PurpleMonkeyDishwasher

1 Answers

2
votes

This can be done using woocommerce_coupon_is_valid filter hook this way:

add_filter( 'woocommerce_coupon_is_valid', 'check_if_coupons_are_valid', 10, 3 );
function check_if_coupons_are_valid( $is_valid, $coupon, $discount ){
    // YOUR ATTRIBUTE SETTINGS BELOW:
    $taxonomy   = 'pa_style';
    $term_slugs = array('swirly', 'circle');

    // Loop through cart items and check for backordered items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        foreach( $cart_item['variation'] as $attribute => $term_slug ) {
            if( $attribute === 'attribute_'.$taxonomy && in_array( $term_slug, $term_slugs ) ) {
                $is_valid = false; // attribute found, coupons are not valid
                break; // Stop and exit from the loop
            }
        }
    }
    return $is_valid;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.