购物车中每NTH件的自定义折扣 [英] Custom discount for every NTH item in the cart

查看:38
本文介绍了购物车中每NTH件的自定义折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自这里的问题寻找适用于我的WooCommerce网站的解决方案.我正在寻找一种仅对购物车中的偶数商品即可在购物车中获得折扣的方法.

I came here from this question here looking to find a solution for my WooCommerce site. I am looking for a way to get a discount in my cart only for even number of items in the cart.

例如:

如果购物车中只有1件商品:全价
购物车中有2个商品:-两个商品的(减号) 2 $
购物车中有5件商品:-4件商品中的(减号) 2 $(如果购物车中的商品数量奇数.总有1件商品具有完整价格)

If there's only 1 item in the cart: Full Price
2 Items in the cart: - (minus) 2$ for both of it
5 Items in the cart: - (minus) 2$ for 4 of it (if there's odd number of items in the cart. 1 item will always have the full price)

顺便说一句,我所有的产品价格都一样.

By the way, all of my products are having the same price.

有人在我提到的问题链接上为那个人提供帮助时,有人可以帮助我吗?

Would someone be able to help me on this, as someone helped for the guy on the question link I've mentioned?

推荐答案

这是您的自定义函数挂在 woocommerce_cart_calculate_fees 动作钩上的,它将满足您的期望:

Here is your custom function hooked in woocommerce_cart_calculate_fees action hook, that will do what you are expecting:

add_action( 'woocommerce_cart_calculate_fees','cart_conditional_discount', 10, 1 );
function cart_conditional_discount( $cart_object ) {

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

    $cart_count = 0;

    foreach($cart_object->get_cart() as $cart_item){
        // Adds the quantity of each item to the count
        $cart_count += $cart_item["quantity"];
    }

    // For 0 or 1 item
    if( $cart_count < 2 ) {
        return;
    }
    // More than 1
    else {
        // Discount calculations
        $modulo = $cart_count % 2;
        $discount = (-$cart_count + $modulo);

        // Adding the fee
        $discount_text = __('Discount', 'woocommerce');
        $cart_object->add_fee( $discount_text, $discount, false );
    }
}

代码会出现在您活动的子主题(或主题)的function.php文件或任何插件文件中.

此代码已经过测试并且可以正常工作.

This code is tested and works.

这篇关于购物车中每NTH件的自定义折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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