2016-12-16 77 views
2

我正在尝试为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); 
} 

,但不能设法使其与修改与价格挂钩的工作。

我该如何做到这一点?

感谢。

回答

2

下面是使用基于车小计不含税量的条件加入这个渐进的百分比为负费做到这一点,所以有优惠:

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

+0

哇,那真的很有帮助。非常感谢! –

+0

有什么方法可以在购物车中显示折扣吗? –

+0

折扣只出现在我的结帐页面,购物车价格显示是没有折扣的全价。 –

相关问题