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

BMA*_*MIT 4 php wordpress cart discount woocommerce

在我的 WooCommerce 网站中,我有一些价格相同的产品80 美元
\n我想按产品数量添加折扣。

\n\n

逻辑是这样的:

\n\n
if (Products Quantity is 2){\n   // the original product price change from 80$ to 75$ each.\n}\n\nif(Products Quantity is 3 or more){\n   //the original product price change from 80$ to 70$ each.      \n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

例如,

\n\n
\n

如果顾客选择了 2 个产品,则原价为(80$ x 2)=> 160$。\n
折扣后价格为:(75$ x 2)=> 150$

\n
\n\n

和\xe2\x80\xa6

\n\n
\n

如果访客选择了 3 个产品,则原价将为(80$ x 3)=> 240$。\n
但扣除费用后,将为:(70$ x 3)=> 210$

\n
\n\n

有什么帮助吗?

\n\n

谢谢

\n

Loi*_*tec 5

这个自定义的挂钩函数应该可以达到您的预期。您可以根据单个商品的数量在其中设置渐进折扣限额。

这是代码

## 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

}
Run Code Online (Sandbox Code Playgroud)

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

已在 WooCommerce 2.6.x 和 3.0+ 上测试并运行