【问题标题】:Progressive percent discount based on cart amount基于购物车金额的累进百分比折扣
【发布时间】:2016-12-16 08:27:42
【问题描述】:

我正在尝试为 WooCommerce 制作一个简单的折扣代码,以便在购买前为您提供百分比折扣。假设如果您添加价值 100 美元的产品,您将获得 2% 的折扣,如果您添加价值 250 美元的产品,您将获得 4% 的折扣,等等。

我发现的唯一东西是:

// 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);
}

但是无法设法使其与修改钩子的价格一起工作。

我怎样才能做到这一点?

【问题讨论】:

    标签: php wordpress woocommerce cart discount


    【解决方案1】:

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

    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 - Conditional Progressive Discount based on number of items in cart

    参考:WooCommerce class - WC_Cart - add_fee() method

    【讨论】:

    • 哇,这真的很有帮助。非常感谢!
    • 有什么方法可以在购物车中显示折扣吗?
    • 折扣只显示在我的结帐页面,在购物车中显示的价格是没有折扣的全价。
    猜你喜欢
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2020-11-04
    • 2020-11-27
    • 2020-12-02
    相关资源
    最近更新 更多