本文介绍了如何使用 WooCommerce 的 woocommerce_cart_calculate_fees 钩子,实现在购物车同时包含指定分类(例如 "drinks" 和 "bundles")的商品时,自动添加费用的功能。文章提供了详细的代码示例,并解释了如何正确地检查购物车中是否同时存在多个指定分类的商品,从而避免错误地应用费用。
在 WooCommerce 商店中,有时需要根据购物车中商品的特定组合来应用费用或折扣。例如,如果客户同时购买了 "drinks" 和 "bundles" 分类的商品,你可能想提供一个特别折扣。以下是如何通过自定义函数来实现这一目标。
首先,我们需要利用 woocommerce_cart_calculate_fees 动作钩子。这个钩子允许我们在购物车计算费用时插入自定义逻辑。
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 ); function custom_pcat_fee( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // 需要同时存在的分类 slug $must_categories = array('drinks','bundles'); $fee_amount = 0; $product_cat = array(); // 遍历购物车中的商品 foreach( $cart->get_cart() as $cart_item ){ $terms = get_the_terms( $cart_item['product_id'], 'product_cat' ); if (is_array($terms)) { // 检查 $terms 是否为数组 foreach ($terms as $term) { $product_cat[] = $term->slug; } } } $product_cat = array_unique( $product_cat ); foreach ( $must_categories as $key => $must_cat ) { if( in_array($must_cat, $product_cat) ){ $fee_amount = -1; }else{ $fee_amount = 0; break; } } // 添加费用 if ( $fee_amount < 0 ){ // 最后一个参数控制是否启用税费 WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false ); } }
代码解释:
注意事项:
总结:
这段代码提供了一个灵活的解决方案,可以根据购物车中商品的分类组合来应用费用或折扣。通过修改 $must_categories 数组,你可以轻松地调整需要同时存在的分类。 记住,在将此代码添加到你的主题或插件之前,请务必进行测试。
以上就是WooCommerce:当购物车同时包含特定分类商品时添加费用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号