In a recent Business Bloomer Club Slack thread, a member sought guidance on a common WooCommerce customization: creating a coupon that offers a percentage discount if the customer buys more than a specific quantity of a given product.
While WooCommerce’s default coupon settings allow you to apply a discount to individual products, there’s no built-in option to add quantity-based conditions to the discount. However, with a bit of custom code, you can create a solution that meets this need.
Here’s a breakdown of how to implement this requirement with a filter hook and some custom PHP.
The following code snippet leverages the woocommerce_coupon_is_valid
filter hook. This filter hook validates the coupon and allows you to introduce specific conditions for its application. In this case, we’ll modify the coupon’s validity based on the quantity purchased:
add_filter( 'woocommerce_coupon_is_valid', 'bbloomer_coupon_valid_item_total_above', 9999, 3 );
function bbloomer_coupon_valid_item_total_above( $valid, $coupon, $discount ) {
// Check if the coupon is linked to specific product IDs
if ( count( $coupon->get_product_ids() ) > 0 ) {
$valid = false;
// Loop through the items in the cart
foreach ( $discount->get_items_to_validate() as $item ) {
if ( $item->product && ( in_array( $item->product->get_id(), $coupon->get_product_ids(), true ) || in_array( $item->product->get_parent_id(), $coupon->get_product_ids(), true ) ) ) {
// Replace 'XYZ' with the minimum quantity threshold
if ( (float) $item->product->get_price() * (float) $item->quantity > XYZ ) $valid = true;
break;
}
}
// Throw an exception if conditions aren’t met
if ( ! $valid ) {
throw new Exception( __( 'Sorry, this coupon is not applicable to selected products.', 'woocommerce' ), 109 );
}
}
return true;
}
In this code:
- Line 1: We attach a function to the
woocommerce_coupon_is_valid
filter, setting priority to a high value (9999
) to ensure it executes last. - Lines 4-5: Check if the coupon applies to specific products by validating against product IDs set within the coupon configuration.
- Line 8: Replace
XYZ
with the minimum total (product price multiplied by quantity) to meet the discount requirement. - Lines 12-14: If the purchase condition isn’t met, an error message appears, indicating the coupon isn’t applicable.
This code provides a flexible way to apply discounts conditionally based on quantity for specific products, empowering you to create customized promotions in WooCommerce without relying on external plugins. Remember to thoroughly test the snippet in a staging environment to ensure it works as expected!