This code snippet excludes product with a specific WooCommerce product_tag from being included in any coupon discount. Simply replace “kits” with the slug of the product_tag you want to exclude. has_term() also accepts an array in the first argument.
add_filter('woocommerce_coupon_is_valid_for_product', 'exclude_product_from_coupon_by_tag', 12, 4);
function exclude_product_from_coupon_by_tag($valid, $product, $coupon, $values ){
// Check if the Product has the term
if( $product->is_type( 'simple' ) ){
$has_term = has_term('kits', 'product_tag', $product->get_id());
} elseif( $product->is_type( 'variation' ) ){
$has_term = has_term('kits', 'product_tag', $product->get_parent_id());
}
// Set the Return
if($has_term === true){
return false;
}else{
return true;
}
}
Update: once again, variable products got the best of me. In WooCommerce, the product_tag is associated with the ‘top level’ product. For simple products, this would be the post itself. However, variations store the product_tag with the parent product. The code has been updated to account for this.