
本文介绍如何使用 WooCommerce 的钩子函数,实现当购物车同时包含特定分类(例如“饮品”和“捆绑商品”)的商品时,自动添加费用的功能。通过遍历购物车商品,获取其所属分类,并判断是否同时包含所有指定分类,从而实现灵活的费用管理。
在 WooCommerce 商店中,有时需要根据购物车中商品的分类组合来应用不同的费用或折扣。例如,当购物车同时包含“饮品”和“捆绑商品”时,可以给予一定的折扣。以下代码演示了如何实现这一功能。
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 (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 ){
// 最后一个参数表示是否启用税费 (true or false)
WC()->cart->add_fee( __( "Kombucha Bundle Discount", "woocommerce" ), $fee_amount, false );
}
}
登录后复制
代码解释:
- add_action( ‘woocommerce_cart_calculate_fees’,’custom_pcat_fee’, 20, 1 );: 此行代码将 custom_pcat_fee 函数挂载到 woocommerce_cart_calculate_fees 钩子上。这意味着每次 WooCommerce 计算购物车费用时,都会执行 custom_pcat_fee 函数。
- if ( is_admin() && ! defined( ‘DOING_AJAX’ ) ) return;: 此检查确保代码仅在前台购物车计算时执行,而不是在管理后台或 AJAX 请求中执行。
- $must_categories = array(‘drinks’,’bundles’);: 定义一个数组 $must_categories,其中包含需要同时包含的分类别名。
- foreach( $cart->get_cart() as $cart_item ): 遍历购物车中的每个商品。
- $terms = get_the_terms( $cart_item[‘product_id’], ‘product_cat’ );: 使用 get_the_terms 函数获取当前商品的所有分类信息,并将其存储在 $terms 变量中。
- foreach ($terms as $term): 循环获取到的分类信息,并将分类别名存储在 $product_cat 数组中。
- $product_cat = array_unique( $product_cat );: 使用 array_unique 函数移除 $product_cat 数组中的重复分类。
- foreach ( $must_categories as $key => $must_cat ): 遍历 $must_categories 数组,检查购物车是否同时包含所有指定的分类。
- if( in_array($must_cat, $product_cat) ): 使用 in_array 函数检查当前分类是否存在于 $product_cat 数组中。如果存在,则将 $fee_amount 设置为 -1。
- else{ $fee_amount = 0; break; }: 只要有一个分类不存在,就将 $fee_amount 设置为 0,并跳出循环。
- WC()->cart->add_fee( __( “Kombucha Bundle Discount”, “woocommerce” ), $fee_amount, false );: 如果 $fee_amount 小于 0,则使用 WC()->cart->add_fee 函数将费用添加到购物车中。
注意事项:
- 确保将代码添加到你的主题的 functions.php 文件或自定义插件中。
- 将 $must_categories 数组中的分类别名替换为你需要检查的实际分类别名。
- 根据需要调整 $fee_amount 的值。
- get_the_terms() 函数可能返回 false 或者 WP_Error 对象,在使用前应该进行判断。建议添加 is_array($terms) 判断,避免在 $terms 为空时报错。
- array_unique 用于移除重复分类,避免同一个商品属于多个相同分类导致误判。
总结:
通过使用 WooCommerce 提供的钩子函数和 PHP 数组操作,可以轻松实现根据购物车商品分类组合来添加费用的功能。 这使得你可以灵活地控制购物车费用,并为客户提供更个性化的购物体验。 记住要根据你的具体需求修改代码,并在生产环境中使用前进行充分测试。
以上就是WooCommerce:当购物车同时包含指定分类的商品时添加费用的详细内容,更多请关注php中文网其它相关文章!