Woocommerce - Product Page - How to create AJAX on "Add To Cart" button? Woocommerce - Product Page - How to create AJAX on "Add To Cart" button? wordpress wordpress

Woocommerce - Product Page - How to create AJAX on "Add To Cart" button?


We can use ajax from archive page. it's easy -

Remove old button which submiting form:

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

Add ajax-link from archive page to single product page:

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

P.S. JS Callback. For example you can show popup with links "Back to shop" and "Cart" or "Checkout"

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


Just add the following attributes to the Add to Cart button to enable the Ajax button.

<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>

The ajax_add_to_cart add_to_cart_button classes, and the data-product_id="<?php echo get_the_ID(); ?>" data-product_sku="<?php echo esc_attr($sku) ?>" attributes are required.

No need to apply any action or filter.


Please start by reading this page:

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

First you need to add some code to your functions.php for example:

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 cartdie();}

Then you have to add some javascript code that triggers the add to cart and makes a call to the function:

  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;    });});

This is just an example of how it can be done. Although its very basic. This javascript checks for links with the classname .add-to-cart and checks the rel attribute for the corresponding product. It then sends the product id to the php class. There you need to add code to add the corresponding product to the cart.

I suggest you search some more about the topic to make it suit your needs. Good luck.