Exclude products with specific attributes terms from WooCommerce coupons Exclude products with specific attributes terms from WooCommerce coupons wordpress wordpress

Exclude products with specific attributes terms from WooCommerce coupons


The linked code from your question is for product variation type. Now to make it work for simple products and variable products (without targeting specific variations attributes terms), you will use the following:

add_filter( 'woocommerce_coupon_is_valid', 'custom_coupon_validity', 10, 3 );function custom_coupon_validity( $is_valid, $coupon, $discount ){    // YOUR ATTRIBUTE SETTINGS BELOW:    $taxonomy   = 'pa_brand'; // Set the taxonomy (start always with "pa_" + the slug)    $term_names = array('Apple', 'Sony'); // Set your term NAMES to be excluded    $term_ids = array(); // Initializing    // Convert term names to term Ids    foreach ( $term_names as $term_name ) {        // Set each term id in the array        $term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id;    }    // Loop through cart items and check for backordered items    foreach ( WC()->cart->get_cart() as $cart_item ) {        $product = $cart_item['variation_id'] > 0 ? wc_get_product($cart_item['product_id']) : $cart_item['data'];        // Loop through product attributes        foreach( $product->get_attributes() as $attribute => $values ) {            if( $attribute === $taxonomy && array_intersect( $values->get_options(), $term_ids ) ) {                $is_valid = false; // attribute found, coupons are not valid                break; // Stop and exit from the loop            }        }    }    return $is_valid;}

Code goes in functions.php file of the active child theme (or active theme). Tested and works for simple and variable products on last WooCommerce version.