我基本上有3个产品价格。单品 - 全价,6 包 - 5% 折扣,24 包 10% 折扣。但是,例如,如果客户要购买 25 个,则需要一包 24 个,包括 10% 折扣 + 1 个单件全价商品,而对于 14 个,则需要 2 个 6 包 5% 折扣和 2 个单件全价。我一直在努力解决它,任何人都可以就我哪里出错或解释我应该使用的逻辑提供一些建议吗?我真的很感激。
更新了我现在改变了我的方法,但还没有完全实现。有人从这里得到任何提示吗?
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);
}
}
}
}
}