WooCommerce特定分类商品总额低于99美元时禁用指定配送方式问题
实现方案
统计逻辑说明
你只需要在现有代码的注释位置补充遍历购物车、分类匹配累加的逻辑即可:
- 初始化枕头类商品总金额变量
$subtotal_pillows为0 - 遍历全部购物车商品,使用WooCommerce原生
has_term()函数判断商品是否属于目标PILLOWS分类 - 分类匹配的商品,将其对应小计金额累加到总金额变量中
完整修改后代码
add_filter( 'woocommerce_package_rates', 'unset_shipping_below_free', 10, 2 ); function unset_shipping_below_free( $rates, $package ) { $categories = array('PILLOWS'); // 注意这里要填你枕头分类的实际slug $threshold = 99; // 阈值金额 $subtotal_pillows = 0; $cart = WC()->cart; $cart_items = $cart->get_cart(); // 统计枕头类商品总金额 foreach ( $cart_items as $item ) { // 判断商品是否属于枕头分类,product_cat是WooCommerce商品分类的固定分类法 if ( has_term( $categories, 'product_cat', $item['product_id'] ) ) { // 累加商品小计,若需要计算含税金额可改为 $item['line_subtotal'] + $item['line_subtotal_tax'] $subtotal_pillows += $item['line_subtotal']; } } if ( $subtotal_pillows < $threshold ) { if ( isset( $rates['free_shipping:4'] ) ) { unset( $rates['free_shipping:4'] ); } if ( isset( $rates['flexible_shipping_single:5'] ) ) { unset( $rates['flexible_shipping_single:5'] ); } } return $rates; }
注意事项
- 代码里的
PILLOWS需要替换为你后台枕头分类的实际slug,不是分类名称 - 代码放到主题的functions.php文件或者自定义代码片段插件中即可生效
- 测试前记得清空WooCommerce缓存,避免配送方式缓存导致效果不显示
内容的提问来源于stack exchange,提问作者Tim
相关产品推荐
相关产品推荐

