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

问题描述

我正在尝试为WooCommerce创建一个简单的折扣代码,以便在购买前给您一定的折扣.假设如果添加价值100美元的产品,您将获得2%的折扣;如果添加价值250美元的产品,则可获得4%的折扣,等等.

I am trying to make a simple discount code for WooCommerce that gives you a percent discount before buying. Lets say that if you add products worth $100 you get 2% discount and if you add products worth $250 you get 4%, etc.

我发现的唯一东西是:

// Hook before calculate fees
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');

/**
 * Add custom fee if more than three article
 * @param WC_Cart $cart
 */
function add_custom_fees( WC_Cart $cart ){
    if( $cart->cart_contents_count < 3 ){
        return;
    }

    // Calculate the amount to reduce
    $discount = $cart->subtotal * 0.1;
    $cart->add_fee( 'You have more than 3 items in your cart, a 10% discount has been added.', -$discount);
}

但是无法设法通过用价格钩子来修改钩子.

But could not manage to make it work with the modifying the hooks with those for the price.

我该如何实现?

推荐答案

以下是使用基于购物车小计总税额的条件将累进百分比添加为负费用的方法,因此可以享受折扣:

Here is the way to do it using conditions based on cart subtotal excl tax amount to add this progressive percentage as a negative fee, so a discount:

add_action( 'woocommerce_cart_calculate_fees','cart_price_progressive_discount' );
function cart_price_progressive_discount() {

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

    $has_discount = false;
    $stotal_ext = WC()->cart->subtotal_ex_tax;

    // Discount percent based on cart amount conditions
    if( $stotal_ext >= 100 && $stotal_ext < 250  ) {
        $percent = -0.02;
        $percent_text = ' 2%';
        $has_discount =true;
    } elseif( $stotal_ext >= 250  ) {
        $percent = -0.04;
        $percent_text = ' 4%';
        $has_discount =true;
    } 
    // Calculation
    $discount = $stotal_ext * $percent;

    // Displayed text
    $discount_text = __('Discount', 'woocommerce') . $percent_text;

    if( $has_discount ) {
        WC()->cart->add_fee( $discount_text, $discount, false );
    }
    // Last argument in add fee method enable tax on calculation if "true"
}

这会出现在您活动的子主题(或主题)的function.php文件中,也可能出现在任何插件文件中.

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

类似: WooCommerce-有条件累进折扣根据购物车中的商品数量

参考: WooCommerce类-WC_Cart-add_fee()方法

这篇关于基于购物车金额的渐进百分比折扣的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 21:13