仅在Woocommerce中的第二个项目有数量折扣 [英] Quantity discount on 2nd item only in Woocommerce

查看:84
本文介绍了仅在Woocommerce中的第二个项目有数量折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为所有产品实现全球折扣,但仅限于第二个产品.

I want to achieve a global discount for all products but only for the 2nd product item.

我是什么意思? 如果客户购买夹克",则不会给予折扣.

What do I mean? If the customer buys "Jacket" no discount is given.

客户购买两种夹克"产品.第二个夹克"提供20%的折扣.

Customer buys two of the "Jacket" product. 20% discount is given on the second "Jacket".

客户购买了五个夹克"产品.在第二个夹克"上仍然只有20%的折扣.

Customer buys five of the "Jacket" product. Still only 20% discount on the 2nd "Jacket".

它对所有简单和可变产品均适用.

It should work for all both simple and variable products.

我设法弄清楚了这件事,我正在寻求有关如何使折扣仅适用于第二项的帮助.

I managed to figure this much out and I'm asking for help with how to make the discount apply to only the 2nd item.

代码如下:

add_filter('woocommerce_product_get_price', 'fifty_percent_on_second_product', 90, 2 );
add_filter('woocommerce_product_get_regular_price', 'fifty_percent_on_second_product', 90, 2 );
function fifty_percent_on_second_product( $price, $product ) {
    if ( is_user_logged_in() ) { 

        I do not know what to do here

}   
    return $price;   
}

有人知道如何进行这项工作吗?如果是这样,请帮助我.

Does anyone know how to make this work? If so, please help me.

推荐答案

您只能使用Fee API通过这种方式在第二项商品上获得折扣(20%):

You could use the Fee API to get a discount (20%) on the 2nd item only this way:

add_action( 'woocommerce_cart_calculate_fees', 'second_item_discount', 10, 1 );
function second_item_discount( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 20; // 20%
    $discount   = 0;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {
        // When quantity is more than 1
        if( $cart_item['quantity'] > 1 ){
            // 20% of the product price as a discount
            $discount += wc_get_price_excluding_tax( $cart_item['data'] ) * $percentage / 100;
        }
    }
    if( $discount > 0 )
        $cart->add_fee( __( '2nd item discount', 'woocommerce' ) , -$discount );
}

代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.

Code goes in function.php file of your active child theme (or active theme). Tested and works.

这篇关于仅在Woocommerce中的第二个项目有数量折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆