You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce点击移除商品时减数量,更新购物车触发重复操作问题

WooCommerce购物车移除链接改为数量减1的问题修复

需求:点击WooCommerce购物车商品的移除链接时,若商品数量大于1,则将数量减1而非直接删除。

原代码尝试通过woocommerce_remove_cart_item钩子修改数量,并用do_shortcode('[woocommerce_cart]')输出购物车HTML来阻止删除操作,但出现后续修改商品数量点击「更新购物车」时,会再次触发减数量的问题。原因是短代码返回的HTML中,_wp_http_referer参数仍保留了remove_item的请求信息:

<input type="hidden" name="_wp_http_referer" value="/courses/cart/?remove_item=2365a4db507862569752334234a29b50&_wpnonce=fd962ed" />

修正方案

放弃直接输出购物车HTML的方式,改用template_redirect钩子在请求初期拦截移除动作,修改数量后重定向到干净的购物车页面,避免referer携带旧参数:

function adjust_cart_remove_action() {
    // 检查是否是移除购物车商品的请求并验证安全签名
    if ( isset( $_GET['remove_item'] ) && isset( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'woocommerce-cart' ) ) {
        $cart_item_key = sanitize_text_field( $_GET['remove_item'] );
        $cart_item = WC()->cart->get_cart_item( $cart_item_key );

        // 若商品数量大于1,执行减1操作而非删除
        if ( $cart_item && $cart_item['quantity'] > 1 ) {
            WC()->cart->set_quantity( $cart_item_key, $cart_item['quantity'] - 1 );
            // 重定向到购物车页面,清除referer中的移除参数
            wp_safe_redirect( wc_get_cart_url() );
            exit;
        }
    }
}
add_action( 'template_redirect', 'adjust_cart_remove_action' );

代码说明

  1. 用template_redirect钩子在页面渲染前处理请求,比woocommerce_remove_cart_item更早拦截移除动作,避免默认删除逻辑触发
  2. 验证nonce确保请求的安全性,防止恶意操作
  3. 修改数量后通过wp_safe_redirect跳转到纯净的购物车页面,此时_wp_http_referer会是干净的购物车URL,不会携带remove_item参数,彻底解决后续更新购物车时重复触发减数量的问题

内容的提问来源于stack exchange,提问作者LM10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:53:12