从 woocommerce 折扣中排除类别

exclude a category from woocommerce discount

以下工作代码是购物车的折扣,至少有 3 件商品不包括 'sale' 产品现在我需要忽略此折扣中的类别 'gift'(如果它在购物车中):

//10% discount at minimum 3 items in cart not for sale items
add_action('woocommerce_cart_calculate_fees' , 'custom_cart_discount', 20, 1);
function custom_cart_discount( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Limitations: Only when there is 5 or more non on sale items in cart
$starting_limit = 3;
// Initialising variables
$not_on_sale_subtotal = $discount = $items_count = 0;
// Iterating through each item in cart
foreach( $cart->get_cart() as $cart_item ){
// For cart items is not on sale
if( ! $cart_item['data']->is_on_sale() ){
    $not_on_sale_subtotal += (float) $cart_item['line_subtotal'];
    $items_count += $cart_item['quantity'];
}
}
// Discount calculation
$discount = $not_on_sale_subtotal * 0.1;
// Applied discount only cart items that are not on sale
if( $discount && $items_count >= $starting_limit )
$cart->add_fee( 'הנחת כמות 10%', -$discount );

我建议使用不同的方法。 WooCommerce 优惠券可让您完全控制想要实现的目标。

首先,在 WC 管理中创建优惠券,可享受 10% 的折扣。然后,使用优惠券设置将其应用到购物车或仅应用到特定 items/categories。您可以在优惠券限制中看到如何准确地将折扣限制在特定类别(使用 include / exclude ),或仅将折扣应用于非促销商品等...

最后,您所要做的就是要求或鼓励客户使用优惠券,或者您自己在后台自动使用优惠券:

WC()->cart->apply_coupon('YouCouponCodeGoesHere');

啊!