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!

Author: Zack Katz

Zack Katz is the President of Katz Web Services and the developer of WordPress plugins with over 700,000 downloads. He lives in Southwest Colorado with his wife and two cats.

6 thoughts on “Prevent Refresh from Adding Another Product in WooCommerce”

Leave a Reply

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