Woocommerce中价格较低的产品的购物车折扣 [英] Cart discount for product that cost less in Woocommerce

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

问题描述

对于价格较低的产品,如何在产品购物车中应用折扣?

How can I apply a discount in products cart for product that costs less?

例如:
我的购物车中有两种产品:一种成本150美元,另一种成本200美元.我只想对价格较低的产品(在本例中为第一个)应用10%的折扣.

For example:
I have two product in cart: one cost 150$ and one 200$. I would like to apply a 10 percent discount only for product that cost less, in this case the first one.

我有此代码,但它仅适用于购物车中的第二个产品:

I have this code but it works only for the second product in cart:

add_filter( 'woocommerce_before_calculate_totals', 'discount_on_2nd_cart_item', 10, 1 );
function discount_on_2nd_cart_item( $cart_object ) {

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

    // Initialising
    $count = 0;
    $discount = 0.10; // 10 %
    $discounted = 0;
    // Iterating though each cart items
    foreach ( $cart_object->get_cart() as $cart_item ) {
        $count++;
        if( 2 == $count){ // Second item only
            $price = $cart_item['data']->get_price(); // product price
            $discounted_price = $price - ($price * $discount); // calculation
            $discounted = $price - $discounted_price;
            // Set the new price
            //$cart_item['data']->set_price( $discounted_price );
            break; // stop the loop
        }
    }

    $cart_object->add_fee( "Discount (10%) on second product", -$discounted, true );
}

推荐答案

对于购物车费用,您应该这样使用woocommerce_cart_calculate_fees专用钩子:

For Cart fees, you should use woocommerce_cart_calculate_fees dedicated hook instead this way:

add_action('woocommerce_cart_calculate_fees', 'discount_on_cheapest_cart_item', 20, 1 );
function discount_on_cheapest_cart_item( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // Only for 2 items or more
    if ( $cart->get_cart_contents_count() < 2 ) return;

    // Initialising
    $percentage = 10; // 10 %
    $discount = 0;
    $item_prices = array();

    // Loop though each cart items and set prices in an array
    foreach ( $cart->get_cart() as $cart_item ) {
        $product_prices_excl_tax[] = wc_get_price_excluding_tax( $cart_item['data'] );
    }
    sort($product_prices_excl_tax);

    $discount = reset($product_prices_excl_tax) * $percentage / 100;

    $cart->add_fee( "Discount on cheapest (".$percentage."%)", -$discount );
}

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

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

这篇关于Woocommerce中价格较低的产品的购物车折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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