我想向woocommerce添加一个功能,当将一个类别中的12-23件商品添加到购物车时,该功能将计算10%的折扣。
然后添加24-47个类别的商品,将有15%的折扣。
如果最后添加此类别的48+件商品,将有20%的折扣。
实际的代码示例将非常棒,因为我是woocommerce的新手
已更新 — 已纠正代码错误,并在输出的折扣文本中添加了增强功能
这里是挂钩在[[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文件中。
add_fee()