如何设置WooCommerce特定分类商品仅作为追加商品时享受折扣
WooCommerce 指定分类商品折扣优化(仅当购物车含其他分类商品时生效)
原代码存在两个核心问题:一是变量名不统一(定义了$categorise_ids却使用未定义的$product_ids),二是未判断购物车是否包含非指定分类的商品,导致仅购买指定分类商品时仍触发折扣。以下是修正后的完整代码:
/** * 为指定分类商品添加折扣(仅当购物车含其他分类商品时生效) * @param WC_Cart $cart */ add_action( 'woocommerce_cart_calculate_fees', 'target_category_product_discount' ); function target_category_product_discount( $cart ) { // 配置项 $target_cat_ids = array(1795, 1732, 1725); // 指定分类ID $discount_percent = 10; // 折扣百分比(10%) $has_target_items = false; $has_other_items = false; $target_subtotal = 0; // 指定分类商品的总金额 // 遍历购物车商品 foreach ( $cart->get_cart() as $cart_item ) { $product_id = $cart_item['product_id']; $variation_id = $cart_item['variation_id']; // 检查当前商品是否属于指定分类 $is_target_category = has_term( $target_cat_ids, 'product_cat', $variation_id ? $variation_id : $product_id ); if ( $is_target_category ) { $has_target_items = true; // 累加指定分类商品的金额(考虑数量) $target_subtotal += $cart_item['line_subtotal']; } else { $has_other_items = true; } } // 触发折扣的条件:同时存在指定分类商品和非指定分类商品 if ( $has_target_items && $has_other_items ) { $discount_amount = $target_subtotal * $discount_percent / 100; $cart->add_fee( __( '指定分类商品折扣', 'woocommerce' ), -$discount_amount ); } }
关键修改说明:
- 变量名规范:将原代码中混乱的
$categorise_ids/$product_ids统一为$target_cat_ids,避免未定义变量错误 - 状态判断:新增
$has_target_items和$has_other_items两个状态,准确判断购物车商品组成 - 精准折扣计算:单独统计指定分类商品的总金额,确保折扣仅作用于目标商品,而非整个购物车
- 条件修正:只有当购物车同时包含指定分类和非指定分类商品时,才触发折扣
内容的提问来源于stack exchange,提问作者Александр Арамович
相关产品推荐
相关产品推荐

