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

如何为WooCommerce自定义加购按钮添加AJAX功能避免页面重载

WooCommerce自定义加购按钮AJAX无刷新实现方案

第一步:修改原有按钮输出逻辑

你需要先调整原来的按钮渲染代码,给按钮加上必要的自定义属性,同时阻止默认跳转行为,修改后的完整PHP代码如下:

add_action( 'woocommerce_after_add_to_cart_button', 'additional_simple_add_to_cart', 20 );
function additional_simple_add_to_cart() {
    
    global $product;

    // 仅对简单商品生效
    if( ! $product->is_type('simple') ) return;
                
    // 仅对指定分类商品生效
    if ( has_term( array('bier', 'cider', 'getraenke'), 'product_cat', $product->get_id() ) ) {
        // 输出AJAX校验用的nonce,防止CSRF攻击
        wp_nonce_field( 'woocommerce-add_to_cart', 'add_to_cart_nonce' );
        
        // 父布局容器
        echo '<div class="flex-container-pack-wrapper">';
            
        // 左侧布局容器
        echo '<div class="flex-container-pack-child left">';
            
            // 库存≥6时显示6件加购按钮
            if( $product->get_stock_quantity() >= 6 ) {
                $class = 'single_add_to_cart_button-6 button alt ajax-pack-add-to-cart'; // 新增共同类名用于JS监听
                $style = 'display: inline-block; margin-top: 12px;';
                $button_text = __( "6er Pack", "woocommerce" );

                // 按钮新增data属性存储商品ID和购买数量,href改为javascript:void(0)阻止默认跳转
                echo '<a rel="no-follow" href="javascript:void(0)" class="'.$class.'" style="'.$style.'" data-product_id="'.esc_attr($product->get_id()).'" data-quantity="6">'.$button_text.'</a>';
                                
            } else {
                echo '<a class="single_sold_out_button button alt disabled ">6er Pack<p class="pack_soldout">(Ausverkauft)</p></a>';
            }
            
            echo '</div>';
            
            // 右侧布局容器
            echo '<div class="flex-container-pack-child right">';

            // 库存≥12时显示12件加购按钮
            if( $product->get_stock_quantity() >= 12 ) {
                $class = 'single_add_to_cart_button-12 button alt ajax-pack-add-to-cart'; // 新增共同类名用于JS监听
                $style = 'display: inline-block; margin-top: 12px;';
                $button_text = __( "12er Pack", "woocommerce" );

                // 按钮新增data属性存储商品ID和购买数量,href改为javascript:void(0)阻止默认跳转
                echo '<a rel="no-follow" href="javascript:void(0)" class="'.$class.'" style="'.$style.'" data-product_id="'.esc_attr($product->get_id()).'" data-quantity="12">'.$button_text.'</a>';
            } else {
                echo '<a class="single_sold_out_button button alt disabled ">12er Pack<p class="pack_soldout">(Ausverkauft)</p></a>';
            }

            echo '</div>';
            
            echo '</div>';
            
            // 配送信息容器
            echo '<div class="container_pack_wrapper_shipping_ino">';
            
            global $product;
            $seller = get_post_field( 'post_author', $product->get_id());
            $author  = get_user_by( 'id', $seller );
            $vendor = dokan()->vendor->get( $seller );

            $store_info = dokan_get_store_info( $author->ID );

            if ( !empty( $store_info['store_name'] ) ) { 
                echo '<p class="shipping_info">Wähle 6, 9-12 oder 24 Biere einer Brauerei aus.</p>';
                printf( '<i class="fas fa-angle-double-right pack"></i><a class="vendor_pack_info" href="%s">Mehr von %s</a>', $vendor->get_shop_url(),  $vendor->get_shop_name() );
                echo '<p class="shipping_info_extra">*Spezial Angebote z.B Probierpakete sind von dieser Beschränkung ausgeschlossen. Versand wird je Brauerei berechnet.</p>';
            }
      
            echo '</div>';
        }
}

第二步:添加前端AJAX交互逻辑

你可以将以下JS代码添加到主题的自定义JS文件中,或者通过WordPress自定义后台的「自定义CSS/JS」功能插入:

jQuery(function($) {
    // 监听自定义加购按钮的点击事件
    $('.ajax-pack-add-to-cart').on('click', function(e) {
        e.preventDefault(); // 阻止默认行为
        
        const $button = $(this);
        const productId = $button.data('product_id');
        const quantity = $button.data('quantity');
        const nonce = $('#add_to_cart_nonce').val();
        
        // 按钮添加加载状态,防止重复点击
        $button.addClass('loading disabled').text('添加中...');
        
        // 发送AJAX请求到WooCommerce原生加购接口
        $.ajax({
            type: 'POST',
            url: wc_add_to_cart_params.ajax_url,
            data: {
                action: 'woocommerce_ajax_add_to_cart',
                product_id: productId,
                quantity: quantity,
                nonce: nonce
            },
            success: function(response) {
                if (response.error && response.product_url) {
                    alert(response.message);
                    $button.removeClass('loading disabled').text(quantity + 'er Pack');
                    return;
                }
                
                // 加购成功后更新购物车碎片(同步更新页面上的购物车数量、金额等信息)
                $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $button]);
                
                // 恢复按钮状态,可自行替换为你需要的成功提示
                $button.removeClass('loading disabled').text('添加成功');
                setTimeout(() => {
                    $button.text(quantity + 'er Pack');
                }, 1500);
            },
            error: function() {
                alert('加购失败,请刷新页面后重试');
                $button.removeClass('loading disabled').text(quantity + 'er Pack');
            }
        });
    });
});

第三步:功能验证

修改完成后清空缓存测试即可,默认会兼容WooCommerce原生的加购成功提示、购物车数量同步逻辑,你也可以根据自己的需求自定义加载样式、成功提示效果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:06:08