I would like to have a conditional progressive discount based on number of items in cart. After you added 2 products to the cart, you get a discount. More products you add and more discount you get.
For example:
- 1 product – full price (No Discount)
- 2 products – full price with 5% discount of the combined price
- 3 products – full price with 10% discount of the combined price
- 4 products – full price with 15% discount of the combined price
- And so on …
I have search over internet without any success. When searching about discounts I just fall on WooCommerce coupon feature or I get some old wrong code…
Any idea? How can I do it?
Is it possible?
Thanks.
Update - October 2018 (code improved)
Yes its possible to use a trick, to achieve this. Normally for discounts on cart we use in WooCommerce coupons. Here coupons are not appropriated. I will use here a negative conditional fee, that becomes a discount.
The calculation:
— The item count is based on quantity by item and total of items in cart
— The percent is 0.05 (5%) and it grows with each additional item (as you asked)
— We use the discounted subtotal (to avoid adding multiple collapsing discounts made by coupons)
The code:
add_action( 'woocommerce_cart_calculate_fees', 'cart_progressive_discount', 50, 1 );
function cart_progressive_discount( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// For 1 item (quantity 1) we EXIT;
if( $cart->get_cart_contents_count() == 1 )
return;
## ------ Settings below ------- ##
$percent = 5; // Percent rate: Progressive discount by steps of 5%
$max_percentage = 50; // 50% (so for 10 items as 5 x 10 = 50)
$discount_text = __( 'Quantity discount', 'woocommerce' ); // Discount Text
## ----- ----- ----- ----- ----- ##
$cart_items_count = $cart->get_cart_contents_count();
$cart_lines_total = $cart->get_subtotal() - $cart->get_discount_total();
// Dynamic percentage calculation
$percentage = $percent * ($cart_items_count - 1);
// Progressive discount from 5% to 45% (Between 2 and 10 items)
if( $percentage < $max_percentage ) {
$discount_text .= ' (' . $percentage . '%)';
$discount = $cart_lines_total * $percentage / 100;
$cart->add_fee( $discount_text, -$discount );
}
// Fixed discount at 50% (11 items and more)
else {
$discount_text .= ' (' . $max_percentage . '%)';
$discount = $cart_lines_total * $max_percentage / 100;
$cart->add_fee( $discount_text, -$discount );
}
}
Code goes in function.php file of your active child theme. Tested and works.
When using FEE API for discounts (a negative fee), taxes are always applied.
References:
- WooCommerce - Adding shipping fee for free user plan
- WooCommerce - Make a set of coupons adding a fixed fee to an order
- WooCommerce class - WC_Cart - add_fee() method