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

Adding a discount by cart items conditionally based on the item quantity

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

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

我找到的最接近的是:

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

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

谢谢。

This code will not work in Woocommerce 3+

See: :

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

这是代码:

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 文件或任何插件文件。

此代码已经过测试并有效。