programing

Woocommerce - Product 페이지 - "Add To Cart" 버튼에서 AJAX를 작성하는 방법

nicegoodjob 2023. 4. 4. 22:53
반응형

Woocommerce - Product 페이지 - "Add To Cart" 버튼에서 AJAX를 작성하는 방법

AJAX에서 사용할 수 있는 상품 페이지에 Add To Cart 버튼을 만들고 싶습니다.어떻게 해야 하죠?제품 페이지에서 장바구니에 추가하면 페이지가 갱신됩니다.AJAX에서는 어떻게 하면 작동합니까?

아카이브의 "Quick View"에 있는 "Add to cart" 버튼은 Ajax에서 작동하며, 매우 좋지만 제품 페이지에서 동일한 작업을 수행할 수 있는 방법은 무엇입니까?

제품 페이지에서 "Take me Home"을 클릭하면 선택한 속성을 가진 제품이 Ajax에 의해 카트에 추가되고 카트가 열리며(메뉴의 가방 이미지 위에 마우스를 올리면) 가방 이미지가 흔들립니다.

[ Add to Cart ]버튼에 다음 속성을 추가하여 [Ajax]버튼을 유효하게 합니다.

<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" aria-label="Add “<?php the_title_attribute() ?>” to your cart"> 
Add to Cart 
</a>

ajax_add_to_cart add_to_cart_button클래스 및 data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>"Atribute는 필수입니다.

작업이나 필터를 적용할 필요가 없습니다.

아카이브 페이지에서 에이잭스를 사용할 수 있습니다.간단해 -

다음 양식을 제출하는 오래된 버튼을 제거합니다.

remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );

아카이브 페이지에서 단일 제품 페이지에 ajax-link 추가:

add_action( 'woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30 );

추신 JS 콜백예를 들어 "Back to shop", "Cart" 또는 "Checkout" 링크가 있는 팝업을 표시할 수 있습니다.

$('body').on('added_to_cart',function(){
    // Callback -> product added
    //$('.popup').show();
});

먼저 이 페이지를 읽어주세요.

http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

먼저 몇 가지 코드를 함수에 추가해야 합니다.예를 들어 php:

add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'prefix_ajax_add_foobar' );

function prefix_ajax_add_foobar() {
   $product_id  = intval( $_POST['product_id'] );
// add code the add the product to your cart
die();
}

그런 다음 카트에 추가를 트리거하고 함수를 호출하는 Javascript 코드를 추가해야 합니다.

  jQuery( ".add-to-cart" ).each(function() 
{


    var product_id = jQuery(this).attr('rel');
    var el = jQuery(this);

    el.click(function() {

            var data = {
                action: 'add_foobar',
                product_id: product_id
            };

            jQuery.post('/wp-admin/admin-ajax.php' , data, function(response) {
                if(response != 0) {
                    // do something
                } else {
                    // do something else
                }

            });


        return false;

    });

});

이것은 단지 그것이 어떻게 이루어질 수 있는지를 보여주는 예시일 뿐이다.아주 기본이긴 하지만요.이 Javascript는 클래스명이 .add-to-cart인 링크를 체크하고 대응하는 제품의 rel 속성을 체크합니다.그런 다음 제품 ID를 php 클래스로 전송합니다.여기서 해당 제품을 장바구니에 추가하기 위한 코드를 추가해야 합니다.

당신의 필요에 맞게 주제에 대해 좀 더 검색해 보는 것이 좋습니다.행운을 빌어요.

Woocommerce가 발전했다.이제 해결은 꽤 쉬워진 것 같아요.필요한 것은 "AJAX add to cart buttons in archive(아카이브의 카트 버튼에 AJAX 추가 활성화)"를 체크하고woocommerce_template_loop_add_to_cart()기능.

체크박스 옵션은 [Woocommerce]> [ Settings ]> [ Products ]> [ General ]아래에 있습니다. 체크박스 옵션은 [Woocommerce]> [ Settings ]> [ Products ]> [ General ]아래에 있습니다.

그런 다음 버튼을 출력하는 곳이면 woocommerce_template_loop_add_to_cart()를 사용합니다.

에는 글로벌하게 .woocommerce_template_loop_add_to_cart()일하기 위해.

다음은 이 기능을 사용하는 간단한 예입니다.

add_shortcode( 'buy_again' , 'msp_buy_again_shortcode' );
function msp_buy_again_shortcode(){
    $order_items = msp_get_customer_unique_order_items( get_current_user_id() );
    echo '<div class="owl-carousel owl-theme">';
    foreach( $order_items as $id ){
        $product = wc_get_product( $id );
        global $product;

        if( ! empty( $product ) ){
            ?>
            <div class="card buy-again-product">
                <a class="link-normal" href="<?php echo $product->get_permalink(); ?>">
                    <?php echo $product->get_image( 'woocommerce_thumbnail', array( 'class' => 'card-img-top' ) ) ?>
                    <div class="card-body">
                        <?php echo wc_get_rating_html( $product->get_average_rating(), $product->get_review_count() ) ?>
                        <h5><?php echo $product->get_name(); ?></h5>
                        <p><?php echo $product->get_price_html() ?></p>
                        <?php woocommerce_template_loop_add_to_cart(); ?>
                    </div>
                </a>
            </div>
            <?php
        }
    }
    // loop and display buy again.
    // try to use the official woocommerce loop.

    echo '</div>';

}

이 코드를 파일에 복사합니다.예를 들어 my-theme-wc-single-ajax-add-cart.js 입니다.

function myThemeWc_SingleProductAddToCart(thisObj) {
    if (typeof($) === 'undefined') {
        var $ = jQuery.noConflict();
    }

    var thisForm = thisObj.closest('form');
    var button = thisForm.find('.button');
    var formUrl = thisForm.attr('action');
    var formMethod = thisForm.attr('method');
    if (typeof(formMethod) === 'undefined' || formMethod == '') {
        formMethod = 'POST';
    }
    var formData = new FormData(thisForm[0]);
    formData.append(button.attr('name'), button.val());

    button.removeClass('added');
    button.addClass('loading');

    myThemeWc_SingleProductCartAjaxTask = $.ajax({
        url: formUrl,
        method: formMethod,
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    })
    .done(function(data, textStatus, jqXHR) {
        $(document.body).trigger('wc_fragment_refresh');

        $.when(myThemeWc_SingleProductCartAjaxTask)
        .then(myThemeWc_SingleProductUpdateCartWidget)
        .done(function() {
            button.removeClass('loading');
            button.addClass('added');
            setTimeout(function() {
                button.removeClass('added');
            }, 2000);
        });
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        button.removeClass('loading');
    })
    .always(function(jqXHR, textStatus, errorThrown) {
        $('.cart').off('submit');
        myThemeWc_SingleProductListenAddToCart();
    });
}// myThemeWc_SingleProductAddToCart


function myThemeWc_SingleProductListenAddToCart() {
    if (typeof($) === 'undefined') {
        var $ = jQuery.noConflict();
    }

    $('.cart').on('submit', function(e) {
        e.preventDefault();
        myThemeWc_SingleProductAddToCart($(this));
    });
}// myThemeWc_SingleProductListenAddToCart


/**
 * Update WooCommerce cart widget by called the trigger and listen to the event.
 * 
 * @returns {undefined}
 */
function myThemeWc_SingleProductUpdateCartWidget() {
    if (typeof($) === 'undefined') {
        var $ = jQuery.noConflict();
    }

    var deferred = $.Deferred();

    $(document.body).on('wc_fragments_refreshed', function() {
        deferred.resolve();
    });

    return deferred.promise();
}// myThemeWc_SingleProductUpdateCartWidget


var myThemeWc_SingleProductCartAjaxTask;


// on page load --------------------------------------------
jQuery(function($) {
    $(document.body).on('wc_fragments_refreshed', function() {
        console.log('woocommerce event fired: wc_fragments_refreshed');
    });

    myThemeWc_SingleProductListenAddToCart();
});

프리픽스 「」, 「변수 프리픽스」를 가 있는 경우가 .myThemeWc_당신이 원하는 것을.

이 코드는 원래 WooCommerce 단일 제품 페이지 Add to Cart 버튼을 사용하지만 기능을 중지하고 대신 폼의 모든 값을 그대로 유지하여 ajax를 사용합니다.

그런 다음 이 js 파일을 큐에 넣습니다.

add_action('wp_enqueue_scripts', 'mythemewc_enqueue_scripts');
function mythemewc_enqueue_scripts() {
    if (class_exists('\\WooCommerce') && is_product()) {
        wp_enqueue_script('mythemewc-single-product', trailingslashit(get_stylesheet_directory_uri()) . 'assets/js/my-theme-wc-single-ajax-add-cart.js', ['jquery'], false, true);
    }
}

로딩, 추가된 아이콘을 표시하려면 css 버튼을 코드화해야 할 수 있습니다.
가가 css ss있 ss습다

.woocommerce #respond input#submit.added::after, 
.woocommerce a.btn.added::after, 
.woocommerce button.btn.added::after, 
.woocommerce input.btn.added::after,
.woocommerce .single_add_to_cart_button.added::after {
    font-family: WooCommerce;
    content: '\e017';
    margin-left: .53em;
    vertical-align: bottom;
}
.woocommerce #respond input#submit.loading, 
.woocommerce a.btn.loading, 
.woocommerce button.btn.loading, 
.woocommerce input.btn.loading,
.woocommerce .single_add_to_cart_button.loading {
    opacity: .25;
    padding-right: 2.618em;
    position: relative;
}
.woocommerce #respond input#submit.loading::after, 
.woocommerce a.btn.loading::after, 
.woocommerce button.btn.loading::after, 
.woocommerce input.btn.loading::after,
.woocommerce .single_add_to_cart_button.loading::after {
    font-family: WooCommerce;
    content: '\e01c';
    vertical-align: top;
    font-weight: 400;
    position: absolute;
    right: 1em;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
}

단일 제품에서 아카이브 버튼의 동작을 복제할 수 있습니다.

add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');      function woocommerce_ajax_add_to_cart() {
            $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
            $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
            $variation_id = absint($_POST['variation_id']);
            $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
            $product_status = get_post_status($product_id);

            if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {

                do_action('woocommerce_ajax_added_to_cart', $product_id);

                if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
                    wc_add_to_cart_message(array($product_id => $quantity), true);
                }

                WC_AJAX :: get_refreshed_fragments();
            } else {

                $data = array(
                    'error' => true,
                    'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));

                echo wp_send_json($data);
            }

            wp_die();
        }
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');

function woocommerce_ajax_add_to_cart() {

            $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
            $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
            $variation_id = absint($_POST['variation_id']);
            $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
            $product_status = get_post_status($product_id);

            if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {

                do_action('woocommerce_ajax_added_to_cart', $product_id);

                if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
                    wc_add_to_cart_message(array($product_id => $quantity), true);
                }

                WC_AJAX :: get_refreshed_fragments();
            } else {

                $data = array(
                    'error' => true,
                    'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));

                echo wp_send_json($data);
            }

            wp_die();
        }

자세한 튜토리얼은 이쪽에서 보실 수 있습니다.

https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/

이 플러그인은 백엔드 파트(https://wordpress.org/plugins/woo-ajax-add-to-cart/)에 사용하였습니다.

제품 페이지를 사용하지 않기 때문에 다음 버튼에서 작동하도록 스크립트를 수정했습니다.

(function($) {
    $(document).on('click', '.btn', function(e) {
        var $thisbutton = $(this);

        try {
            var href = $thisbutton.prop('href').split('?')[1];

            if (href.indexOf('add-to-cart') === -1) return;
        } catch (err) {
            return;
        }

        e.preventDefault();

        var product_id = href.split('=')[1];

        var data = {
            product_id: product_id
        };

        $(document.body).trigger('adding_to_cart', [$thisbutton, data]);

        $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.wc_ajax_url.replace(
                '%%endpoint%%',
                'add_to_cart'
            ),
            data: data,
            beforeSend: function(response) {
                $thisbutton.removeClass('added').addClass('loading');
            },
            complete: function(response) {
                $thisbutton.addClass('added').removeClass('loading');
            },
            success: function(response) {
                if (response.error & response.product_url) {
                    window.location = response.product_url;
                    return;
                } else {
                    $(document.body).trigger('added_to_cart', [
                        response.fragments,
                        response.cart_hash
                    ]);

                    $('a[data-notification-link="cart-overview"]').click();
                }
            }
        });

        return false;
    });
})(jQuery);

정보: WooCommerce 2.4.10에서 테스트 완료.

음, 다른 방법으로 추가에서 카트(woocommerce/templates/loop/add-to-cart.php)에 woocommerce 루프를 사용했습니다.

  global $product;

echo apply_filters( 'woocommerce_loop_add_to_cart_link',
    sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
        esc_url( $product->add_to_cart_url() ),
        esc_attr( $product->id ),
        esc_attr( $product->get_sku() ),
        esc_attr( isset( $quantity ) ? $quantity : 1 ),
        $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
        esc_attr( $product->product_type ),
        esc_html( $product->add_to_cart_text() )
    ),
$product );

하지만 문제는 1개의 수량만 추가한다는 것입니다.실제로 1개의 수량을 나열한 코드를 보면 알 수 있습니다.그래서 문제가 있었습니다.그때 저를 구해준사람과 마주칠 때까지.

ps. 1부는 1개만 카트에 넣어 두지만, 2개 이상의 제품을 카트에 추가할 필요가 있는 분들을 위한 솔루션을 추가했습니다.

add-to-matrix.displaces.disl

jQuery( document ).on( 'click', '.product_type_simple', function() { 

var post_id = jQuery(this).data('product_id');//store product id in post id variable
var qty = jQuery(this).data('quantity');//store quantity in qty variable

jQuery.ajax({
    url : addtocart.ajax_url, //ajax object of localization
    type : 'post', //post method to access data
    data : 
    {
        action : 'prefix_ajax_add_foobar', //action on prefix_ajax_add_foobar function
        post_id : post_id,
        quantity: qty
    },

    success : function(response){

            jQuery('.site-header .quantity').html(response.qty);//get quantity
            jQuery('.site-header .total').html(response.total);//get total

            //loaderContainer.remove();
            alert("Product Added successfully..");        
    }

});

return false;
});

ajax woocomerce를 다른 페이지에서 작동시키려면 필요합니다.기능을 합니다.php

붙여넣기:

remove_action ('woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30);

add_action ('woocommerce_single_product_summary', 'woocommerce_template_loop_add_to_cart', 30);

바닥글에서.php는 다음과 같이 붙여넣습니다.

<script>
$ ('body'). on ('add_to_cart', function () {
     // Callback -> product added
     // $ ('. popup'). show ();
});
</script>

의기양양하게 일하는 나를 위해서.이것이 Ajax와 함께 하는 가장 간단한 해결책이라고 생각합니다.

<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button add-cart" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>"> + Add to cart</a>

Eh Jewel의 답변을 사용했지만, 카트에 제품을 추가하면 커스텀 JS를 추가했습니다.이것으로 원하는 대로 페이지를 갱신할 수 있는 최종 AJAX 프로세스가 완료됩니다.

완전성을 위해 사용한HTML 코드는 다음과 같습니다(Eh Jewel과 동일).

<a href="<?php echo $product->add_to_cart_url() ?>" value="<?php echo esc_attr( $product->get_id() ); ?>" class="ajax_add_to_cart add_to_cart_button" data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" aria-label="Add “<?php the_title_attribute() ?>” to your cart"> Add to Cart </a>

다음으로 커스텀 JS 비트의 경우:

$(window).on('load', function() {
  $('body').on( 'added_to_cart', function( added_to_cart, cart, cart_hash, button ){
    // Put the functionality here. Debugging shows you what you have to work with:
    console.log('added_to_cart object');
    console.log(added_to_cart);
    console.log('cart object');
    console.log(cart);
    console.log('cart_hash object');
    console.log(cart_hash);
    console.log('button object');
    console.log(button);
  });
});

언급URL : https://stackoverflow.com/questions/25892871/woocommerce-product-page-how-to-create-ajax-on-add-to-cart-button

반응형