2016-12-02 79 views
2

我想爲woocommerce添加一個功能,當一個類別的12-23項添加到購物車時,該功能將計算10%的折扣。基於數量計算的產品類別的購物車折扣

然後,如果24 - 47項目的類別添加它將是一個15%的折扣。

最後如果添加48+這個類別的項目,這將是一個20%的折扣。因爲我是新來woocommerce

+1

您是否嘗試過的插件,可以做這些類型的折扣?也許https://wordpress.org/plugins-wp/pricing-deals-for-woocommerce/ –

+0

我嘗試了一些插件沒有成功。我嘗試了pricegain-for-woocommerce –

+0

@DustySatterlee剛剛重新更新我的答案有一個小錯誤...代碼中的2個錯誤...現在正在完美工作。 – LoicTheAztec

回答

0

更新

實際的代碼示例將是真棒 - 更正代碼錯誤,並在輸出打折文本

這裏加入的增強是函數來鉤掛在woocommerce_cart_calculate_fees掛鉤將基於購物車項目數量計算爲該特定類別(或子類別)打折扣。

這是代碼:

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

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

    // Set HERE your category (can be an ID, a slug or the name) 
    $category = 34; // or a slug: $category = 'wine'; 

    $category_count = 0; 
    $category_total = 0; 
    $discount = 0; 

    // Iterating through each cart item 
    foreach($cart_object->get_cart() as $cart_item): 

     if(has_term($category, 'product_cat', $cart_item['product_id'])): 
      $category_count += $cart_item['quantity']; 
      $category_total += $cart_item["line_total"]; // calculated total items amount (quantity x price) 
     endif; 

    endforeach; 

    $discount_text = __('Quantity discount of ', 'woocommerce'); 

    // ## CALCULATIONS ## 
    if ($category_count >= 12 && $category_count < 24) { 
     $discount -= $category_total * 0.1; // Discount of 10% 
     $discount_text_output = $discount_text . '10%'; 
    } elseif ($category_count >= 24 && $category_count < 48) { 
     $discount -= $category_total * 0.15; // Discount of 15% 
     $discount_text_output = $discount_text . '15%'; 
    } elseif ($category_count >= 48) { 
     $discount -= $category_total * 0.2; // Discount of 20% 
     $discount_text_output = $discount_text . '20%'; 
    } 

    // Adding the discount 
    if ($discount != 0 && $category_count >= 12) 
     $cart_object->add_fee($discount_text_output, $discount, false); 

    // Note: Last argument in add_fee() method is related to applying the tax or not to the discount (true or false) 
} 

注:add_fee()方法最後一個參數是與應用稅或不打折......

代碼進行測試並完全功能。

代碼發送到您活動的子主題(或主題)的function.php文件中。或者也可以在任何插件php文件中使用。


類似的:Discount for Certain Category Based on Total Number of Products

相關問題