2017-04-10 82 views
1

我從this question here來到這裏尋找我的WooCommerce網站的解決方案。我正在尋找一種方法,只在購物車中有數量的物品時才能在購物車中獲得折扣。購物車中每個NTH商品的自定義折扣

例如:

如果只有1購物車中物品:全價
2個項目在購物車: - (減) $ 2兩的它在車
5項: - (減) $ 2的它4(如果有奇數個在車中的項目1項將始終擁有全價)。

順便說一句,我所有的產品都具有相同價錢。

有人能幫助我,因爲有人幫助我提到的問題鏈接上的人?

回答

2

這裏是你的自定義功能woocommerce_cart_calculate_fees行動掛鉤鉤住,會做你期待什麼:

add_action('woocommerce_cart_calculate_fees','cart_conditional_discount', 10, 1); 
function cart_conditional_discount($cart_object) { 

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

    $cart_count = 0; 

    foreach($cart_object->get_cart() as $cart_item){ 
     // Adds the quantity of each item to the count 
     $cart_count += $cart_item["quantity"]; 
    } 

    // For 0 or 1 item 
    if($cart_count < 2) { 
     return; 
    } 
    // More than 1 
    else { 
     // Discount calculations 
     $modulo = $cart_count % 2; 
     $discount = (-$cart_count + $modulo); 

     // Adding the fee 
     $discount_text = __('Discount', 'woocommerce'); 
     $cart_object->add_fee($discount_text, $discount, false); 
    } 
} 

代碼放在您的活動子主題(或主題)的function.php文件或也在任何插件文件中。

此代碼已經過測試並可正常工作。

+0

我認爲'$ discount'會是'$ discount =( - $ cart_count + $ modulo)* 2;'... – Reigel

+0

@Reigel問題不是很清楚......顯然OP想要讓一個累進折扣2 $ each 2 items ...我的代碼適用於這種情況。 – LoicTheAztec

+0

是一致認爲它不清楚。 – Reigel