gpt4 book ai didi

php - 根据商品数量有条件地按购物车商品添加折扣

转载 作者:可可西里 更新时间:2023-11-01 01:14:43 25 4
gpt4 key购买 nike

我已经建立了一个 Woocommerce 商店,并希望为所有产品设置基于 12(一盒)的倍数的特定折扣。我尝试了很多折扣插件,但没有找到我要找的东西。

例如,如果我订购 12 件 X 产品,我将获得 10% 的折扣。如果我订购 15 件 X 产品,前 12 件可享受 10% 的折扣,后三件是全价。如果我订购 24 件,那么 10% 的折扣适用于所有 24 件产品 X。

我找到的最接近的是:Discount for Certain Category Based on Total Number of Products

但这在最后应用为折扣(实际上是负费用),我想在产品旁边的购物车中显示折扣,就像正常折扣一样。

如果产品已经打折,我还需要禁用此折扣。

谢谢。

最佳答案

This code will not work in Woocommerce 3+

See: Cart item discount based on quantity in Woocommerce 3:

是的,这也是可能的,使用 woocommerce_before_calculate_totals 中的自定义函数,为每个购物车商品进行自定义计算并单独替换它们的价格(匹配您的条件和计算) Action Hook 。

这是代码:

add_action( 'woocommerce_before_calculate_totals', 'custom_discounted_cart_item_price', 10, 1 );
function custom_discounted_cart_item_price( $cart_object ) {

$discount_applied = false;

// Set Here your targeted quantity discount
$t_qty = 12;

// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {

## Get cart item data
$item_id = $item_values['data']->id; // Product ID
$item_qty = $item_values['quantity']; // Item quantity
$original_price = $item_values['data']->price; // Product original price

// Getting the object
$product = new WC_Product( $item_id );


// CALCULATION FOR EACH ITEM
// when quantity is up to the targetted quantity and product is not on sale
if( $item_qty >= $t_qty && !$product->is_on_sale() ){
for($j = $t_qty, $loops = 0; $j <= $item_qty; $j += $t_qty, $loops++);

$modulo_qty = $item_qty % $t_qty; // The remaining non discounted items

$item_discounted_price = $original_price * 0.9; // Discount of 10 percent

$total_discounted_items_price = $loops * $t_qty * $item_discounted_price;

$total_normal_items_price = $modulo_qty * $original_price;

// Calculating the new item price
$new_item_price = ($total_discounted_items_price + $total_normal_items_price) / $item_qty;


// Setting the new price item
$item_values['data']->price = $new_item_price;

$discount_applied = true;
}
}
// Optionally display a message for that discount
if ( $discount_applied )
wc_add_notice( __( 'A quantity discount has been applied on some cart items.', 'my_theme_slug' ), 'success' );
}

This make exactly the discount that you are expecting separately for each item in cart (based on it's quantity) and not for items that are in sale. But you will not get any label (text) indicating a discount in the line items of cart.

Optionally I display a notice when a discount is applied to some cart items…

代码位于您的事件子主题(或主题)的 function.php 文件中或任何插件文件中。

此代码已经过测试并且可以工作。

关于php - 根据商品数量有条件地按购物车商品添加折扣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com