2016-12-16 79 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

折扣只出現在我的結帳頁面,購物車價格顯示是沒有折扣的全價。 –

相關問題