How to Add Quantity Based Discounts in WooCommerce Programmatically
This tutorial will show you how to use custom code to automatically adjust the price per product based on the quantity in the cart.
Here’s how the discount logic works:
- If a customer buys more than 1 and up to 10 products, the price per product drops from $80 to $75.
- If a customer buys 10 or more products, the price per product drops to $70.
Here is the complete code snippet
// Apply Quantity-Based Discount in WooCommerce
add_action( 'woocommerce_cart_calculate_fees', 'quantity_based_discount', 10, 1 );
function quantity_based_discount( $cart ) {
// Check if in admin and not doing AJAX
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Initialize discount amount
$discount = 0;
// Loop through each item in the cart
foreach ( $cart->get_cart() as $cart_item ) {
$qty = $cart_item['quantity'];
$original_price = 80; // Original price per item
// Calculate the discount based on quantity
if ( $qty >= 1 && $qty <= 10 ) {
$discount += $qty * ($original_price - 75); // $5 discount per item
} elseif ( $qty > 10 ) {
$discount += $qty * ($original_price - 70); // $10 discount per item
}
}
// Apply the discount to the cart
if ( $discount > 0 ) {
$cart->add_fee( __( 'Quantity Discount' ), -$discount );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'quantity_based_discount', 10, 1 );
function quantity_based_discount( $cart ) {
// Check if in admin and not doing AJAX
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Initialize discount amount
$discount = 0;
// Loop through each item in the cart
foreach ( $cart->get_cart() as $cart_item ) {
$qty = $cart_item['quantity'];
$original_price = 80; // Original price per item
// Calculate the discount based on quantity
if ( $qty >= 1 && $qty <= 10 ) {
$discount += $qty * ($original_price - 75); // $5 discount per item
} elseif ( $qty > 10 ) {
$discount += $qty * ($original_price - 70); // $10 discount per item
}
}
// Apply the discount to the cart
if ( $discount > 0 ) {
$cart->add_fee( __( 'Quantity Discount' ), -$discount );
}
}