本文介绍了基于 Woocommerce 中购物车项目数的有条件累进百分比折扣的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据购物车中的商品数量享受有条件的累进折扣.将 2 件产品添加到购物车后,您将获得折扣.您添加更多产品并获得更多折扣.

I would like to have a conditional progressive discount based on number of items in cart. After you added 2 products to the cart, you get a discount. More products you add and more discount you get.

例如:

  • 1 件产品 - 全价(无折扣)
  • 2 件产品 - 全价,总价的 5% 折扣
  • 3 种产品 - 全价,总价的 10% 折扣
  • 4 种产品 - 全价,总价的 15% 折扣
  • 等等......

我在互联网上搜索过但没有成功.在搜索折扣时,我只是使用了 WooCommerce 优惠券功能,或者我得到了一些旧的错误代码......

I have search over internet without any success. When searching about discounts I just fall on WooCommerce coupon feature or I get some old wrong code…

有什么想法吗?我该怎么做?

Any idea? How can I do it?

有可能吗?

谢谢.

推荐答案

是的,可以使用技巧来实现这一点.通常用于我们在 WooCommerce 优惠券中使用的购物车折扣.这里不使用优惠券.我将在这里使用负按条件收费,这变成了折扣.

Yes its possible to use a trick, to achieve this. Normally for discounts on cart we use in WooCommerce coupons. Here coupons are not appropriated. I will use here a negative conditional fee, that becomes a discount.

计算:
— 商品数量基于商品数量和购物车中的商品总数
— 百分比为 0.05 (5%),并且随着每个项目的增加而增加(如您所问)
— 我们使用折扣小计(避免添加多个优惠券的折叠折扣)

The calculation:
— The item count is based on quantity by item and total of items in cart
— The percent is 0.05 (5%) and it grows with each additional item (as you asked)
— We use the discounted subtotal (to avoid adding multiple collapsing discounts made by coupons)

代码:

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

    // For 1 item (quantity 1) we EXIT;
    if( $cart->get_cart_contents_count() == 1 )
        return;

    ## ------ Settings below ------- ##

    $percent = 5; // Percent rate: Progressive discount by steps of 5%
    $max_percentage = 50; // 50% (so for 10 items as 5 x 10 = 50)
    $discount_text = __( 'Quantity discount', 'woocommerce' ); // Discount Text

    ## ----- ----- ----- ----- ----- ##

    $cart_items_count = $cart->get_cart_contents_count();
    $cart_lines_total = $cart->get_subtotal() - $cart->get_discount_total();

    // Dynamic percentage calculation
    $percentage = $percent * ($cart_items_count - 1);

    // Progressive discount from 5% to 45% (Between 2 and 10 items)
    if( $percentage < $max_percentage ) {
        $discount_text .=  ' (' . $percentage . '%)';
        $discount = $cart_lines_total * $percentage / 100;
        $cart->add_fee( $discount_text, -$discount );
    }
    // Fixed discount at 50% (11 items and more)
    else {
        $discount_text .=  ' (' . $max_percentage . '%)';
        $discount = $cart_lines_total * $max_percentage / 100;
        $cart->add_fee( $discount_text, -$discount );
    }
}

代码位于活动子主题的 function.php 文件中.经过测试并有效.

当使用 FEE API 进行折扣(负费用)时,总是要征税.

参考:

这篇关于基于 Woocommerce 中购物车项目数的有条件累进百分比折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 17:59