我想免费赠送三件产品。如果有人添加了更多数量的商品,我只想免费提供一个数量。这意味着从小计中扣除某一数量的价格。例如:一种产品的价格为 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;
$targeted_ids = [344,345,346]; // Here define the valid products Ids
$qty_threshold = 2; // Here define the minimum quantity required
foreach ( $cart->get_cart() as $cart_item ) {
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
$quantity = $cart_item['quantity'];
if ( $quantity >= $qty_threshold ) {
$discounted_price = $cart_item['data']->get_price() / $quantity * ($quantity - 1);
$cart_item['data']->set_price( $discounted_price );
}
}
}
}
或者(以同样的方式),您可以添加全局计算的折扣小计,例如:
add_action( 'woocommerce_cart_calculate_fees', 'action_cart_calculate_fees', 30, 1 );
function action_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$targeted_ids = [344,345,346]; // Here define the valid products Ids
$qty_threshold = 2; // Here define the minimum quantity required
$discount = 0; // Initializing
foreach ( $cart->get_cart() as $cart_item ) {
if ( in_array( $cart_item['product_id'], $targeted_ids ) ) {
if ( $cart_item['quantity'] >= $qty_threshold ) {
$discount += $cart_item['data']->get_price();
}
}
}
if( $discount > 0 ) {
$cart->add_fee( __( "Quantity discount", "woocommerce" ), -$discount);
}
}
两种方法都应该有效。
关于php - WooCommerce 中一件免费产品的数量折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76986989/