本教程旨在解决 WooCommerce 中一个常见的需求:当购物车同时包含多个特定分类的商品时,自动添加或减少费用。我们将通过代码示例,详细讲解如何实现这一功能,并提供注意事项,确保代码的稳定性和可维护性。该方法通过检查购物车中是否存在所有指定的商品分类,从而实现精准的费用控制。
在 WooCommerce 商店中,经常需要根据购物车中的商品种类来调整费用。例如,当购物车同时包含“饮品”和“套餐”两个分类的商品时,可能需要提供一个折扣。以下是如何通过自定义函数来实现这一需求。
实现步骤
添加自定义函数到 functions.php 文件:
将以下代码添加到你的 WordPress 主题的 functions.php 文件中,或者使用 Code Snippets 插件添加。
add_action( 'woocommerce_cart_calculate_fees','custom_pcat_fee', 20, 1 ); function custom_pcat_fee( $cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // 需要同时存在的分类别名数组 $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 ($terms && ! is_wp_error($terms)) { // 确保 $terms 不是 WP_Error 对象 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 ){ // 最后一个参数表示是否启用税费 (true 或 false) WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false ); } }
代码解释:
注意事项
总结
通过以上步骤,你就可以在 WooCommerce 商店中实现当购物车同时包含特定分类的商品时添加费用的功能。记住,理解代码的逻辑和注意事项,并根据你的实际需求进行调整,才能更好地应用到你的 WooCommerce 商店中。
以上就是WooCommerce:当购物车同时包含特定分类的商品时添加费用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号