programing

아약스 wooCommerce 3 제품 변형 카트에 추가 버튼

css3 2023. 11. 1. 22:32

아약스 wooCommerce 3 제품 변형 카트에 추가 버튼

여기 이 버튼이 있어요.이 버튼의 사용은 상품 ID가 237, 변형 ID가 208673, 블루투스의 속성_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>

저는 그것을 작동시키기 위해 제품 변형을 위해 커스텀 아약스 애드 투 카트를 단독으로 사용합니다.

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>

보시다시피 저는 버튼을 사용하지 않습니다.hrefajax를 통해 데이터를 게시할 때 속성.

속성의 경우 하나 이상의 쌍을 가지면 다음과 같이 각 쌍을 혼수 상태로 분리합니다.

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_fragment_refresh');
                        }, 500);
                    }
                },
                error: function (error) {
                    $(a).addClass('failed').html('Add to cart failed!');
                    console.log(error);
                }
            });
        });
    });
    </script>
    <?php
}

코드가 작동합니다.활성 하위 테마(또는 활성 테마)의 php 파일입니다.테스트를 거쳐 작동합니다.

플러그인("Wocommerce Ajax add to cart for variable products")을 사용하여 변화의 속성(: 색상)과 프론트엔드의 수량을 선택한 후에 눌러야 하는 "Add to cart" 버튼을 Ajaxify 할 수 있습니다.이 플러그인을 기본적으로 사용하지 않으면 "수레에 추가"를 누르면 페이지가 새로 고쳐집니다.

enter image description here

언급URL : https://stackoverflow.com/questions/50631834/ajax-add-to-cart-button-for-product-variation-in-woocommerce-3