Home is for the experience. Projects are for the ones who are interested!

Detect Add To Cart Action – Woocommerce Add To Cart

Detect Add To Cart Action – Woocommerce Add To Cart

Sometimes you need to detect add to cart action in woocommerce.  Once the customer has added any product in cart we will be able to notice him, or we can fire any event we need. For this action you need to have Ajax option "Enable AJAX add to cart buttons on archives" enabled. You can check if you have this options from: WooCoommerce -> Products. The checkbox should be in the first options. This option enable the ajax on list products page.

With option enabled we need to listen at add to cart event. The easiest way to do this is with jquery because with two lines of code we can see when a new product is added to cart.

Due to Woocommerce scripts which adds everything you need on add to cart button, meaning product_id you can get it then in your jquery script, once you have the product id you can get any details about the product you need by ajax. 

The jquery code for this event is the following:

jQuery( 'body' ).on( 'added_to_cart', function( e, fragments, cart_hash, this_button ) {
    alert('product added to cart');
} );

 

Most of the times I used only this_button parameter because if you console.log with this parameter you will see it will return all atributes of clicked button so, in our case the product id we need. Then by ajax you can send the product id in a php file and return the product details or cross sells and up sells related to this product.

I will come back with a much more detailed tutorial and with a Youtube video to understand well how this is working.

If you have any question please let them in comments section. 

Leave a Reply

Your email address will not be published. Required fields are marked *