Categories
Code

Prevent Refresh from Adding Another Product in WooCommerce

Update: this issue has been resolved. WooCommerce now replaces the `add-to-cart` query arg with `added-to-cart` on success.

Prevent items from being mistakenly added to the cart multiple times.

Mountain America Jerky uses the WooCommerce eCommerce plugin for WordPress, and they were having an issue: when users added a product to their cart then refreshed, the item was being added again. Also, when customers added items to their cart, then hit back, they got the dreaded “Confirm Form Resubmission” notice.

To solve this issue, I added a redirection when users added products to their cart. The code hooks into WooCommerce’s `woocommerce_add_to_cart_action` function, located in `/woocommerce/woocommerce-functions.php`.

Here’s the code that you should add to your theme’s `functions.php` file, or to your own custom plugin:

add_action('add_to_cart_redirect', 'resolve_dupes_add_to_cart_redirect');
 
function resolve_dupes_add_to_cart_redirect($url = false) {
 
     // If another plugin beats us to the punch, let them have their way with the URL
     if(!empty($url)) { return $url; }
 
     // Redirect back to the original page, without the 'add-to-cart' parameter.
     // We add the `get_bloginfo` part so it saves a redirect on https:// sites.
     return get_bloginfo('wpurl').add_query_arg(array(), remove_query_arg('add-to-cart'));
 
}

I hope this helps someone else with the same issue!

By Zack Katz

Zack Katz is the founder of GravityKit and TrustedLogin. He lives in Leverett, Massachusetts with his wife Juniper.

9 replies on “Prevent Refresh from Adding Another Product in WooCommerce”

Had to register to tell you a big thanks for this solution. This resolved my issue. Cheers mate!

Holy crap is this real??? This is like the biggest damn problem I had since I lost my sliced bread… I’m actually in awe… I can now disable admin ajax cart fragments and… speed up my site and… not have annoying duplicate procucts being added lol… i love you<3

Comments are closed.