Enabling AJAX Add to Cart on single product views, with X overlay

X Theme and Pro Theme6 Comments

One simple tweak I make on many of my Woocommerce based websites is to enable the AJAX add to cart functionality. In many cases, having the user directed to a cart page isn’t ideal for your shop, and a hard reload to the same page is just silly. Someone in the Themeco community asked about how to do this, so I’m sharing the code I use. It can be applied to any site with any theme that doesn’t have this built in already, but my code here has the added perk of including the X/Pro “Added to Cart” overlay. Continuity is good UX, afterall.

Please note this only works on simple type products.

This gist has two files. The first is the custom javascript you need to make it work. You can place this in your customizer, or better yet, save it to a file in your child theme and enqueue it only on single product pages. The second file is your PHP code that can go directly into functions.php in your child theme.

The above code should work as is for you on any X or Pro site. For tweaking from there, one thing I see a lot of people do is toggle their cart off canvas to fly out after an item has been added to cart. While you could put it in the AJAX success function, a better way would be to hook into the javascript event “added_to_cart” to do it globally.

Hope that helps a few of you out, feel free to drop a comment below if needed!

6
Leave a Reply

avatar
  Subscribe  
Notify of
Thomas
Thomas

Thanks for sharing. Can you explain how to toggle the cart off canvas after adding an item to the cart?

Thomas
Thomas

And 2nd question: How to use this code WITH redirect to cart?

German Kokum
German Kokum

thanks for this code

I have been dealing with this tutorial without luck

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