WooCommerce 基于购物车总重量在运费费率表添加通知的实现
问题原因
- 你用的
woocommerce_package_rates是专门修改配送方式列表的过滤器,这个钩子执行时直接输出内容,既不会渲染到你需要的运费总计行位置,还可能导致配送区域AJAX刷新异常。 - 原有代码的条件判断未加大括号包裹逻辑块,只有
unset行受「local_pickup可用」条件约束,echo语句只要重量达标就会执行,不符合你要求的双条件触发逻辑。
调整方案
我们拆分两个功能模块实现需求:保留原有配送方式隐藏逻辑,新增专门的前端通知渲染钩子,完整可运行代码如下:
// 1. 处理配送方式隐藏,同时记录通知触发状态 add_filter( 'woocommerce_package_rates', 'adjust_shipping_methods_and_record_flag', 9999, 2 ); function adjust_shipping_methods_and_record_flag( $rates, $package ) { // 初始化通知标记为不触发 $GLOBALS['show_weight_shipping_notice'] = false; $cart_weight = WC()->cart->get_cart_contents_weight(); // 双条件同时满足才执行逻辑 if ( $cart_weight > 14999 && isset( $rates['local_pickup:1'] ) ) { unset( $rates['flat_rate:2'], $rates['local_pickup:7'] ); // 标记需要展示通知 $GLOBALS['show_weight_shipping_notice'] = true; } return $rates; } // 2. 在运费总计行后输出通知,同时适配购物车页和结账页 add_action( 'woocommerce_cart_totals_after_shipping', 'show_shipping_weight_notice' ); add_action( 'woocommerce_review_order_after_shipping', 'show_shipping_weight_notice' ); function show_shipping_weight_notice() { global $show_weight_shipping_notice; if ( $show_weight_shipping_notice ) { // 可替换为自定义通知内容,自带WooCommerce官方通知样式 echo '<div class="woocommerce-info" style="margin-top:10px;">My notification</div>'; } } // 可选:配送方式修改后缓存不生效时添加,自动清空配送缓存 add_filter( 'woocommerce_shipping_rate_needs_shipping', 'clear_shipping_cache_on_weight_change' ); function clear_shipping_cache_on_weight_change( $needs_shipping ) { if ( is_cart() || is_checkout() ) { WC()->session->set( 'shipping_for_package_0', '' ); } return $needs_shipping; }
使用说明
将代码添加到当前主题的functions.php文件或自定义功能插件中即可生效,可自行替换代码内的My notification为你需要展示的通知内容,不需要结账页展示通知的话删掉对应add_action行即可。
内容的提问来源于stack exchange,提问作者Brecht Schoeters
相关产品推荐
相关产品推荐

