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. 

0 0 votes
Article Rating
Notify of
Newest Most Voted
Inline Feedbacks
View all comments
5 years ago

super helpful article but that I am a complete layman in JS question I have how to get out of this product_id

Asaf Azoulay
Asaf Azoulay
3 years ago

how can i do the same by javascript only?

document.querySelector(‘a.add_to_cart_button’).addEventListener(“click”function(e) {
            var button = this;
            document.body.addEventListener(“added_to_cart”function() {
              // do somthing

this code not working for me…

Asaf Azoulay
Asaf Azoulay
3 years ago
Reply to  Penguin Arts

not working, it working only with jQuery. i want to use javascript…

jQuerydocument.body ).on‘added_to_cart’function(){
// do somthing


Duy Nguyen
Duy Nguyen
3 years ago

Thank you. It is very helpful for me!

Would love your thoughts, please comment.x