我想免费赠送三件产品。如果有人添加了更多数量的商品,我只想免费提供一个数量。这意味着从小计中扣除某一数量的价格。例如:一种产品的价格为 4,添加的总数量为 5。因此小计总计为 20。现在,我想从小计中扣除一个数量的价格。所以,扣除价格后,最终的结果就是小计15。
我已经尝试过这段代码。
$free_items_id = [344,345,346];
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
if ( in_array( $cart_item['product_id'], $free_items_id ) ) {
if ( $cart_item['quantity'] > 1 ) {
$price_to_be_deducted = $cart_item['data']->get_price();
$updated_price = ( $cart_item['quantity'] - 1 ) * $price_to_be_deducted;
$cart_item['data']->set_price( $updated_price );
break;
}
else {
$cart_item['data']->set_price( 0 );
}
}
}
但是此代码将 $updated_price 与产品的总数量相乘。谁能给个解决办法吗
要对一件产品进行折扣,当数量达到 2 件时,请尝试以下操作:
add_action( 'woocommerce_before_calculate_totals', 'action_before_calculate_totals');
function action_before_calculate_totals( $cart ) {
if ((is_admin() && !defined('DOING_AJAX')))
return;
if (did_action('woocommerce_before_calculate_totals') >= 2)
return;
$free_items_id = [344,345,346];
foreach ( $cart->get_cart() as $cart_item ) {
if ( in_array( $cart_item['product_id'], $free_items_id ) ) {
$quantity = $cart_item['quantity'];
if ( $quantity > 1 ) {
$discounted_price = $cart_item['data']->get_price() / $quantity * ($quantity - 1);
$cart_item['data']->set_price( $discounted_price );
}
}
}
}
应该可以。