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

修改WooCommerce添加购物车按钮行为:实现页面锚点跳转

实现无刷新添加购物车并平滑滚动到页面购物车区域

1. 禁用默认刷新并配置AJAX基础支持

将以下代码添加到你的WordPress主题functions.php文件,或自定义功能插件中:

// 取消单产品页添加购物车后的页面跳转
add_filter('woocommerce_add_to_cart_redirect', '__return_false');

// 注册并本地化AJAX所需脚本
add_action('wp_enqueue_scripts', 'load_add_to_cart_ajax_assets');
function load_add_to_cart_ajax_assets() {
    if (is_product()) {
        wp_enqueue_script('wc-add-to-cart');
        wp_localize_script('wc-add-to-cart', 'wc_cart_params', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'product_id' => get_the_ID()
        ));
    }
}

2. 编写自定义JS处理点击与滚动逻辑

通过Elementor的「自定义代码」模块(或主题的自定义JS设置)添加以下代码:

document.addEventListener('DOMContentLoaded', () => {
    const addCartBtn = document.querySelector('.single_add_to_cart_button.button.alt.wp-element-button');
    if (!addCartBtn) return;

    addCartBtn.addEventListener('click', (e) => {
        e.preventDefault(); // 阻止默认刷新行为

        // 收集产品ID与购买数量
        const productId = wc_cart_params.product_id;
        const quantity = document.querySelector('.qty').value || 1;
        const formData = new FormData();
        
        formData.append('action', 'woocommerce_add_to_cart');
        formData.append('product_id', productId);
        formData.append('quantity', quantity);

        // AJAX请求添加到购物车
        fetch(wc_cart_params.ajax_url, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                // 平滑滚动到#shop锚点区域
                const cartSection = document.getElementById('shop');
                if (cartSection) {
                    cartSection.scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
                // 可选:更新页面上的购物车数量显示
                const cartCount = document.querySelector('.cart-contents .count');
                if (cartCount) cartCount.textContent = data.cart_contents_count;
            } else {
                alert(data.data?.message || '添加购物车失败,请重试');
            }
        })
        .catch(err => {
            console.error('购物车请求错误:', err);
            alert('添加购物车时出现异常,请稍后再试');
        });
    });
});

关键注意事项

  • 该方案仅针对简单产品,如果是变量产品,需要额外处理属性参数的收集
  • 确认Elementor设置的锚点元素CSS ID为shop(不要带#前缀)
  • 测试前清空浏览器缓存,确保新脚本生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 03:50:17