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

调用do_shortcode('[woocommerce_cart]')致WooCommerce默认Ajax更新失效

问题解决:WooCommerce自定义输出购物车短代码时Ajax失效

核心原因

直接用echo do_shortcode('[woocommerce_cart]')输出购物车时,WooCommerce默认的购物车Ajax初始化逻辑没被正确触发——编辑器页面会自动加载购物车相关脚本并绑定事件,而自定义输出场景下,这些脚本可能未加载,或者DOM渲染后没有触发初始化事件。

解决方案

1. 强制加载购物车必要脚本

在主题的functions.php中添加代码,确保购物车相关脚本在目标页面加载:

add_action('wp_enqueue_scripts', 'load_wc_cart_scripts');
function load_wc_cart_scripts() {
    // 替换成你输出购物车的页面ID或slug
    if (is_page('custom-cart-page')) {
        // 加载WooCommerce核心购物车脚本
        wp_enqueue_script('wc-cart');
        wp_enqueue_script('woocommerce');
        // 确保加载购物车参数(Ajax请求依赖)
        wp_localize_script('woocommerce', 'wc_cart_params', wc_get_cart_params());
    }
}

2. 手动触发Ajax初始化事件

在输出购物车短代码的位置后,添加JS代码触发购物车初始化:

// 输出购物车短代码
echo do_shortcode('[woocommerce_cart]');
?>
<script>
jQuery(document).ready(function($) {
    // 触发WooCommerce购物车更新事件,初始化Ajax功能
    $(document.body).trigger('wc_cart_updated');
    
    // 额外绑定移除商品的Ajax事件(如果默认绑定失效)
    $(document).on('click', '.cart_item .remove', function(e) {
        e.preventDefault();
        const cartItemKey = $(this).data('cart_item_key');
        
        $.post(wc_cart_params.ajax_url, {
            action: 'woocommerce_remove_cart_item',
            cart_item_key: cartItemKey
        }, function(response) {
            if (response.success) {
                $(document.body).trigger('wc_cart_updated');
            }
        });
    });
});
</script>
<?php

3. 检查输出上下文

确保购物车短代码输出在WooCommerce的标准布局钩子内,比如:

add_action('woocommerce_before_main_content', 'output_custom_cart');
function output_custom_cart() {
    echo do_shortcode('[woocommerce_cart]');
}

这样能保证WooCommerce的样式和脚本上下文正确。

4. 排查冲突

如果以上方法无效,暂时切换到Storefront默认主题,禁用其他第三方插件,排查是否是主题或插件的脚本冲突导致Ajax事件被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 05:42:08