简体   繁体   English

WooCommerce:根据单个商品数量添加折扣

[英]WooCommerce: Add a discount based on individual items quantity

In my WooCommerce website I have a few products with the same price of 80$ .在我的 WooCommerce 网站上,我有一些价格相同的产品80 美元
I want to add a Discount by the products quantity.我想按产品数量添加折扣。

The logic is like that:逻辑是这样的:

if (Products Quantity is 2){
   // the original product price change from 80$ to 75$ each.
}

if(Products Quantity is 3 or more){
   //the original product price change from 80$ to 70$ each.      
}

for example,例如,

if a customer pick 2 products, the original price will be (80$ x 2) => 160$ .如果客户选择 2 个产品,原价将为(80$ x 2) => 160$
But after the discount, it will be: (75$ x 2) => 150$ .但打折后,它将是: (75$ x 2) => 150$

And…和…

if visitor pick 3 products, the original price will be (80$ x 3) => 240$ .如果访客选择 3 个产品,原价将为(80$ x 3) => 240$
But after the fee, it will be: (70$ x 3) => 210$ .但是在费用之后,它将是: (70$ x 3) => 210$

Any help, please?请问有什么帮助吗?

Thanks谢谢

This custom hooked function should do what you expect.这个自定义挂钩函数应该可以满足您的期望。 You can set in it your progressive discount limit based on individual item quantity.您可以根据单个商品数量在其中设置您的累进折扣限制

Here is the code这是代码

## Tested and works on WooCommerce 2.6.x and 3.0+
add_action( 'woocommerce_cart_calculate_fees', 'progressive_discount_by_item_quantity', 10, 1 );
function progressive_discount_by_item_quantity( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
        
    # Progressive quantity until quantity 3 is reached (here)
    # After this quantity limit, the discount by item is fixed
    # No discount is applied when item quantity is equal to 1
        
    // Set HERE the progressive limit quantity discount
    $progressive_limit_qty = 3; //  <==  <==  <==  <==  <==  <==  <==  <==   <==  <==  <==

    $discount = 0;

    foreach( $cart->get_cart() as $cart_item_key => $cart_item ){

        $qty = $cart_item['quantity'];
        
        if( $qty <= $progressive_limit_qty )
            $param = $qty; // Progressive
        else
            $param = $progressive_limit_qty; // Fixed

        ## Calculation ##
        $discount -=  5 * $qty * ($param - 1); 
    }

    if( $discount < 0 )
        $cart->add_fee( __( 'Quantity discount' ), $discount); // Discount

}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.代码位于活动子主题(或主题)的 function.php 文件或任何插件文件中。

Tested and works on WooCommerce 2.6.x and 3.0+在 WooCommerce 2.6.x 和 3.0+ 上测试和工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM