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

WooCommerce迷你购物车优惠券添加及总额动态更新问题:跳转异常

解决WooCommerce迷你购物车优惠券动态更新不跳转问题

我来帮你搞定这个问题!核心问题在于默认的WooCommerce优惠券表单是直接提交到购物车页面的,咱们得改成AJAX异步提交,这样就能在迷你购物车内完成优惠券应用/移除,同时动态更新总额,不用跳转。下面是具体的实现步骤:

1. 修改迷你购物车中的优惠券表单HTML

首先把你现有的表单代码调整成这样,重点是修改表单提交地址、添加专属类名,确保结构适配AJAX请求:

<form class="woocommerce-cart-form mini-cart-coupon-form" action="<?php echo esc_url( admin_url('admin-ajax.php') ); ?>" method="post">
    <div class="coupon">
        <label for="mini-cart-coupon"><?php esc_html_e( 'Coupon:', 'woocommerce' ); ?></label>
        <input type="text" name="coupon_code" class="input-text" id="mini-cart-coupon" value="" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" />
        <button type="submit" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?>"><?php esc_attr_e( 'Apply coupon', 'woocommerce' ); ?></button>
        <?php do_action( 'woocommerce_cart_coupon' ); ?>
        <input type="hidden" name="action" value="mini_cart_apply_coupon">
    </div>
</form>

2. 添加PHP AJAX处理函数

在你的主题functions.php文件中添加以下代码,用来处理优惠券的应用/移除请求,并返回更新后的迷你购物车内容:

// 应用优惠券的AJAX处理(登录/未登录用户均可用)
add_action('wp_ajax_mini_cart_apply_coupon', 'handle_mini_cart_apply_coupon');
add_action('wp_ajax_nopriv_mini_cart_apply_coupon', 'handle_mini_cart_apply_coupon');

function handle_mini_cart_apply_coupon() {
    if (!isset($_POST['coupon_code']) || empty($_POST['coupon_code'])) {
        wp_send_json_error(array('message' => __('Please enter a coupon code.', 'woocommerce')));
    }

    $coupon_code = sanitize_text_field($_POST['coupon_code']);
    $coupon = new WC_Coupon($coupon_code);

    // 校验优惠券有效性
    if (!$coupon->is_valid()) {
        wp_send_json_error(array('message' => __('Invalid coupon code.', 'woocommerce')));
    }

    // 应用优惠券到购物车
    WC()->cart->apply_coupon($coupon_code);

    // 生成更新后的迷你购物车HTML
    ob_start();
    woocommerce_mini_cart();
    $mini_cart_html = ob_get_clean();

    // 获取最新购物车总额
    $cart_total = WC()->cart->get_total();

    wp_send_json_success(array(
        'mini_cart_html' => $mini_cart_html,
        'cart_total' => $cart_total,
        'message' => __('Coupon applied successfully.', 'woocommerce')
    ));
}

// 移除优惠券的AJAX处理(可选,按需添加)
add_action('wp_ajax_mini_cart_remove_coupon', 'handle_mini_cart_remove_coupon');
add_action('wp_ajax_nopriv_mini_cart_remove_coupon', 'handle_mini_cart_remove_coupon');

function handle_mini_cart_remove_coupon() {
    if (!isset($_POST['coupon_code']) || empty($_POST['coupon_code'])) {
        wp_send_json_error(array('message' => __('Invalid coupon code.', 'woocommerce')));
    }

    $coupon_code = sanitize_text_field($_POST['coupon_code']);
    WC()->cart->remove_coupon($coupon_code);

    ob_start();
    woocommerce_mini_cart();
    $mini_cart_html = ob_get_clean();

    $cart_total = WC()->cart->get_total();

    wp_send_json_success(array(
        'mini_cart_html' => $mini_cart_html,
        'cart_total' => $cart_total,
        'message' => __('Coupon removed successfully.', 'woocommerce')
    ));
}

3. 编写JavaScript实现异步提交和页面更新

在主题的functions.php中添加这段JS代码(也可以放到主题的自定义JS文件里),用来拦截表单提交事件、发送AJAX请求并更新页面内容:

add_action('wp_footer', 'mini_cart_coupon_js');

function mini_cart_coupon_js() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            // 处理优惠券应用表单提交
            $('.mini-cart-coupon-form').on('submit', function(e) {
                e.preventDefault();
                const form = $(this);
                const couponCode = form.find('#mini-cart-coupon').val();

                $.ajax({
                    url: form.attr('action'),
                    type: 'POST',
                    data: form.serialize(),
                    beforeSend: function() {
                        form.find('button').prop('disabled', true).text('Applying...');
                    },
                    success: function(response) {
                        if (response.success) {
                            // 更新迷你购物车容器内容
                            $('.widget_shopping_cart_content').html(response.data.mini_cart_html);
                            // 更新页面上的购物车总额(如果有对应元素)
                            $('.cart-total').html(response.data.cart_total);
                            alert(response.data.message);
                        } else {
                            alert(response.data.message);
                        }
                        form.find('button').prop('disabled', false).text('Apply coupon');
                        form.find('#mini-cart-coupon').val('');
                    },
                    error: function() {
                        alert('Something went wrong, please try again.');
                        form.find('button').prop('disabled', false).text('Apply coupon');
                    }
                });
            });

            // 处理优惠券移除(如果添加了移除按钮)
            $(document).on('click', '.mini-cart-remove-coupon', function(e) {
                e.preventDefault();
                const couponCode = $(this).data('coupon');

                $.ajax({
                    url: '<?php echo esc_url( admin_url('admin-ajax.php') ); ?>',
                    type: 'POST',
                    data: {
                        action: 'mini_cart_remove_coupon',
                        coupon_code: couponCode
                    },
                    beforeSend: function() {
                        $('.mini-cart-remove-coupon').prop('disabled', true);
                    },
                    success: function(response) {
                        if (response.success) {
                            $('.widget_shopping_cart_content').html(response.data.mini_cart_html);
                            $('.cart-total').html(response.data.cart_total);
                            alert(response.data.message);
                        } else {
                            alert(response.data.message);
                        }
                        $('.mini-cart-remove-coupon').prop('disabled', false);
                    },
                    error: function() {
                        alert('Something went wrong, please try again.');
                        $('.mini-cart-remove-coupon').prop('disabled', false);
                    }
                });
            });
        });
    </script>
    <?php
}

4. 调整迷你购物车模板(可选)

如果你需要在迷你购物车中显示已应用的优惠券和移除按钮,可以复制woocommerce/cart/mini-cart.php到主题目录下,然后添加这段代码(建议放到总额区域上方):

<?php if ( WC()->cart->has_discount() ) : ?>
    <?php foreach ( WC()->cart->get_coupons() as $code => $coupon ) : ?>
        <div class="applied-coupon">
            <span><?php echo esc_html( $code ); ?></span>
            <a href="#" class="mini-cart-remove-coupon" data-coupon="<?php echo esc_attr( $code ); ?>"><?php esc_html_e( '(Remove)', 'woocommerce' ); ?></a>
        </div>
    <?php endforeach; ?>
<?php endif; ?>

这样设置后,用户在迷你购物车输入优惠券代码点击应用,就会通过AJAX异步处理,直接更新迷你购物车的内容和总额,完全不会跳转到购物车页面了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:27:10