基于数量计算的产品类别的购物车折扣

基于数量计算的产品类别的购物车折扣

问题描述:

我想为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

更新

实际的代码示例将是真棒 - 更正代码错误,并在输出打折文本

这里加入的增强是函数来钩挂在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