I basically have 3 prices for products. Single product – full price, 6 pack – 5% off, 24 pack 10% off. However, if a customer was to buy 25 for example, it would take a pack of 24 including 10% off + 1 single full price item, and for 14 it would take 2 6 packs at 5% off and 2 single full prices. I’ve been trying to get my head around it, could anyone offer some advice of where I have gone wrong or explain the logic I should use? I would really appreciate it.
Updated I have now changed my approach but it is not quite there yet. Any tips from here anyone?
add_action( 'woocommerce_before_calculate_totals', 'quantity_based_pricing', 9999 );
function quantity_based_pricing( $cart ) {
// Define discount rules and thresholds
$threshold1 = 6; // Change price if items = 6
$discount1 = 0.05; // Reduce unit price by 5%
$threshold2 = 24; // Change price if items = 24
$discount2 = 0.1; // Reduce unit price by 10%
$threshold3 = 1;
$discount3 = 0;
$new_price=0;
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$quantity = $cart_item['quantity'];
$price = $cart_item['data']->get_price();
if((int)($quantity/$threshold2)==0){
for($i=0; $i<(int)($quantity/$threshold2);$i++){
$new_price+=$threshold2*$price*(1-$discount2);
}
cart_item['data']->set_price( $new_price );
}
else{
if((int)($quantity/$threshold2)!=0){
for($i=0; $i<(int)($quantity/$threshold2);$i++){
$new_price+=$threshold2*$price*(1-$discount2);
}
$remainder = $quantity % $threshold2;
if((int)($remainder/$threshold1)==0){
for($i=0; $i<(int)($remainder/$threshold2);$i++){
$new_price+=$threshold1*$price*(1-$discount1);
}
cart_item['data']->set_price( $new_price );
}
elseif((int)($remainder/$threshold1)!=0){
for($i=0; $i<(int)($remainder/$threshold2);$i++){
$new_price+=$threshold1*$price*(1-$discount1);
}
$remainder2 = $remainder % $threshold1;
$new_price+= $remainder2 *$price;
cart_item['data']->set_price($new_price);
}
}
}
}
}
2
Answers
You need to get the quantity from the $cart_item[‘quantity’].
This is a solution:
Note! If someone buys 24+5 items this code will only apply the “special” price for the 24 items and then charge full price for the other 5(the user could of course split the order into two and benefit from both discounts)