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

如何阻止WooCommerce购物车验证失败跳转并在商城页显示提示

解决WooCommerce商城页加购限制时的跳转问题

问题说明

使用woocommerce_add_to_cart_validation钩子实现购物车最多添加2件商品的限制后,在商城页点击「加入购物车」触发限制条件时,页面会跳转到商品详情页才显示错误提示,需要改为在商城页直接显示提示且不跳转。

解决方案

1. 修正验证逻辑(覆盖当前加购数量)

原代码仅判断购物车已有商品数量,未计算本次要添加的数量,可能导致超量情况漏拦截。同时调整钩子优先级,确保逻辑优先执行:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_cart_item_limit_validation', 10, 3 );
function custom_cart_item_limit_validation( $passed, $product_id, $quantity ) {
    // 计算购物车已有商品数 + 本次拟添加数量
    $current_cart_count = count(WC()->cart->get_cart());
    $total_after_add = $current_cart_count + $quantity;

    if( $total_after_add > 2 ){
        wc_add_notice( __( "购物车最多只能添加2件商品", "woocommerce" ), "error" );
        $passed = false;
    }
    return $passed;
}

2. 添加JS阻止非AJAX跳转

商城页默认加购按钮未启用AJAX时,验证失败会触发跳转。添加JavaScript拦截默认行为,确保提示在商城页显示:

add_action( 'wp_footer', 'custom_prevent_add_to_cart_redirect' );
function custom_prevent_add_to_cart_redirect() {
    // 仅在商城/商品分类/标签页执行
    if ( ! is_shop() && ! is_product_category() && ! is_product_tag() ) return;
    ?>
    <script>
    jQuery(document).ready(function($) {
        $('.add_to_cart_button').on('click', function(e) {
            // 检测是否存在验证错误提示
            var $errorNotice = $('.woocommerce-error');
            if ( $errorNotice.length > 0 ) {
                e.preventDefault(); // 阻止跳转
                // 滚动到提示位置(可选优化)
                $('html, body').animate({ scrollTop: $errorNotice.offset().top }, 500);
            }
        });
    });
    </script>
    <?php
}

3. 启用AJAX加购(可选优化)

若主题支持AJAX加购,可开启WooCommerce内置功能,彻底避免跳转:

  • 确保主题加购按钮带有ajax_add_to_cart类
  • 进入WooCommerce设置→产品→显示,勾选「启用AJAX添加到购物车按钮存档页面」

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:45:40