Ajax添加到购物车按钮,用于WooCommerce 3中的产品变体

时间:2018-05-31 19:54:26

标签: php jquery ajax wordpress woocommerce

我在这里有这个按钮。使用此按钮是为了向购物车添加产品ID为237,变体ID为208673,以及bluetooth的attribute_pa_option。有没有办法让AJAX这个?

<div class="btnss">
    <span class="price">
        <span class="woocommerce-Price-amount amount">6,999&nbsp;
            <span class="woocommerce-Price-currencySymbol">kr</span>
        </span>
    </span>
    <div class="quantity buttons_added">
        <input type="button" value="-" class="minus">
        <label class="screen-reader-text" for="quantity_5b101f605f067">Quantity</label>
        <input type="number" id="quantity_5b101f605f067" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" aria-labelledby="">
        <input type="button" value="+" class="plus">
    </div>
    <a href="/?add-to-cart=237&variation_id=208673&attribute_pa_option=bluetooth" class="button product_type_simple add_to_cart_button ajax_add_to_cart">Add to cart</a>
</div>

2 个答案:

答案 0 :(得分:3)

为了使其正常工作,我专门为产品变体使用自定义ajax add-to-cart。

1)我先改变了你的按钮html:

<div class="btnss">
    <span class="price">
        <span class="woocommerce-Price-amount amount">6,999&nbsp;
            <span class="woocommerce-Price-currencySymbol">kr</span>
        </span>
    </span>
    <div class="quantity buttons_added">
        <input type="button" value="-" class="minus">
        <label class="screen-reader-text" for="quantity_5b101f605f067">Quantity</label>
        <input type="number" id="quantity_5b101f605f067" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" aria-labelledby="">
        <input type="button" value="+" class="plus">
    </div>
    <a href="#" class="button product_type_variation add_to_cart_button ajax variation" data-product_id="237" data-variation_id="208673" data-quantity="1" data-variation="pa_option=bluetooth">Add to cart</a>
</div>

正如您将看到我没有使用按钮href属性,因为我通过ajax发布数据。

对于您的属性,如果您有多个属性,则将每个对分开一个昏迷,如:

data-variation="pa_option=bluetooth,pa_color=red-shiny"

2)PHP(Wordpress-Ajax)和jQuery(Ajax)代码:

// Wordpress Ajax php: Adding variation to cart
add_action( 'wp_ajax_nopriv_variation_to_cart', 'product_variation_add_to_cart' );
add_action( 'wp_ajax_variation_to_cart', 'product_variation_add_to_cart' );
function product_variation_add_to_cart() {
    if( isset($_POST['pid']) && $_POST['pid'] > 0 ){
        $product_id   = (int) $_POST['pid'];
        $variation_id = (int) $_POST['vid'];
        $quantity     = (int) $_POST['qty'];
        $attributes   = explode(',', $_POST['var']);
        $variation    = array();
        foreach($attributes as $values){
            $values = explode('=', $values);
            $variation['attributes_'.$values[0]] = $values[1];
        }
        WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
        echo true;
    }
    die(); // To avoid server error 500
}

// The Jquery ajax script
add_action( 'wp_footer', 'custom_product_variation_script' );
function custom_product_variation_script() {
    // HERE set the page or the post ID
    $the_id = 102;

    if( ! ( is_page($the_id) || is_single($the_id) ) ) return;

    $view_cart = '<a href="'.wc_get_cart_url().'" class="added_to_cart wc-forward" title="View cart">View cart</a>';
    $adding    = __('Adding to cart…', 'woocommerce');
    ?>
    <script type="text/javascript">
    jQuery( function($){
        // wc_add_to_cart_params is required to continue
        if ( typeof wc_add_to_cart_params === 'undefined' )
            return false;

        var a = 'a.button.ajax.variation',
            b = $(a).html(),
            c = '<?php echo $view_cart; ?>',
            d = '<?php echo $adding; ?>';

        // Sync the data-quantity attribute
        $('input.minus,input.plus').on( 'click blur', function(){
            $(a).attr('data-quantity',$('input.qty').val());
        });
        $('input.qty').on('input click blur', function(){
            $(a).attr('data-quantity',$('input.qty').val());
        })

        $(a).on('click', function(e){
            e.preventDefault();

            $('a.wc-forward').remove();
            $(a).html(d);

            // The Ajax request
            $.ajax({
                type: 'POST',
                url: wc_add_to_cart_params.ajax_url,
                data: {
                    'action': 'variation_to_cart',
                    'pid'   : $(a).attr('data-product_id'),
                    'vid'   : $(a).attr('data-variation_id'),
                    'qty'   : $(a).attr('data-quantity'),
                    'var'   : $(a).attr('data-variation'),
                },
                success: function (response) {
                    if(response){
                        // Update button and refresh minicart fragments
                        setTimeout(function(){
                            $(a).addClass('added').html(b).after(c);
                            $(document.body).trigger('added_to_cart').trigger('wc_fragments_refresh');
                        }, 500);
                    }
                },
                error: function (error) {
                    $(a).addClass('failed').html('Add to cart failed!');
                    console.log(error);
                }
            });
        });
    });
    </script>
    <?php
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。

答案 1 :(得分:0)

您可以使用this plugin (“ Woocommerce Ajax添加到购物车以购买可变产品”)来修饰“添加到购物车” 按钮,在选择前端的变体属性(例如颜色)和数量后,可以按。默认情况下,如果没有此插件,则在您按“添加到购物车”时页面会刷新

enter image description here