WooCommerce点击proceed to checkout进入结账时如何清除页面通知
问题描述
你当前通过如下代码实现购物车页订单总重量不足1kg时的提示功能:
// Add notice on cart when order is less than 1kg add_action('woocommerce_check_cart_items','check_cart_minweight'); function check_cart_minweight(){ global $woocommerce; $minweight = $woocommerce->cart->cart_contents_weight; if( $minweight < 1 ){ wc_add_notice( sprintf( __( 'You have selected %sKg, add more items, orders over 1kg get free shipping', 'woocommerce' ), $minweight ), 'success' ); } }
存在的故障:若购物车商品总重量始终未达到1kg,用户点击Proceed to Checkout进入结账页面后,上述添加的提示通知不会自动清除,会在结账页面持续展示。
故障原因
woocommerce_check_cart_items钩子会在购物车页、结账页两个场景触发,wc_add_notice()生成的通知默认存储在用户会话中不会自动跨页清理,原有逻辑没有做页面场景判断,既没有限制提示仅在购物车页添加,也没有在进入结账页时主动移除对应提示,最终导致通知跨页残留。
修复方案
调整代码逻辑,新增两个判断规则:
- 仅在购物车页面触发重量校验、添加不足1kg的提示
- 非购物车场景(包含结账页)主动遍历清除已添加的重量提示通知,避免残留
修复后完整代码如下:
// 购物车商品总重量不足1kg时展示提示,修复结账页通知残留问题 add_action('woocommerce_check_cart_items','check_cart_minweight'); function check_cart_minweight(){ global $woocommerce; $cart_weight = $woocommerce->cart->cart_contents_weight; $notice_match_str = 'orders over 1kg get free shipping'; // 非购物车页面清除对应重量提示,不新增通知 if( !is_cart() ){ $all_notices = wc_get_notices(); if( !empty($all_notices['success']) ){ foreach( $all_notices['success'] as $index => $notice_content ){ // 匹配到对应重量提示就移除 if( strpos($notice_content, $notice_match_str) !== false ){ wc_clear_notice( $index ); } } } return; } // 仅购物车页执行重量校验 if( $cart_weight < 1 ){ wc_add_notice( sprintf( __( 'You have selected %sKg, add more items, orders over 1kg get free shipping', 'woocommerce' ), $cart_weight ), 'success' ); } }
注意:如果站点开启了多语言,将代码中
$notice_match_str变量的取值替换为你站点实际展示的提示文案中的固定片段即可,确保能匹配到对应通知完成清除。
内容的提问来源于stack exchange,提问作者go-diego-go
相关产品推荐
相关产品推荐

