WooCommerce:移除商品后购物车为空如何即时跳转(无需手动刷新)
解决WooCommerce空购物车即时重定向问题
你的问题根源在于:移除购物车商品是通过AJAX异步操作完成的,页面不会刷新,所以template_redirect钩子只会在页面加载时触发,没法捕捉到AJAX操作后的购物车状态变化。要实现即时跳转,得同时处理后端AJAX回调和前端状态监听。
修改后的完整代码
1. 后端PHP代码(替换你原来的代码)
// 处理页面加载时的空购物车重定向(保留原逻辑) add_action( 'template_redirect', 'empty_cart_redirection' ); function empty_cart_redirection(){ if( is_cart() && WC()->cart->get_cart_contents_count() == 0 ) { wp_safe_redirect( get_permalink( get_option('woocommerce_shop_page_id') ) ); // 用商店页ID替代固定的8,适配性更强 exit; } } // 处理AJAX移除商品后的购物车检查 add_action( 'woocommerce_after_cart_item_removed_action', 'check_empty_cart_after_removal', 10, 2 ); function check_empty_cart_after_removal( $cart_item_key, $cart ){ if( $cart->get_cart_contents_count() == 0 ){ // 给前端返回跳转信号 wp_send_json_success( array( 'redirect' => get_permalink( get_option('woocommerce_shop_page_id') ) ) ); exit; } }
2. 前端JS代码(添加到主题functions.php或自定义JS文件)
jQuery(document).ready(function($){ // 监听购物车商品移除后的AJAX响应 $(document).on('wc_cart_item_removed', function(event, response){ if( response.success && response.data.redirect ){ // 立即跳转到指定页面 window.location.href = response.data.redirect; } }); });
代码说明
- 保留
template_redirect是为了处理用户直接访问空购物车页面的场景; woocommerce_after_cart_item_removed_action钩子会在商品通过AJAX移除后立即触发,此时检查购物车是否为空,若为空则给前端返回跳转地址;- 前端通过
wc_cart_item_removed事件监听AJAX响应,一旦收到跳转信号就立刻执行页面跳转,无需手动刷新。
内容的提问来源于stack exchange,提问作者TI Moonwalk
相关产品推荐
相关产品推荐

