0

We use this type of Add to Cart URL on our site a lot of times: http://yourdomain.com/cart/?add-to-cart=25. The problem is after it redirects to the Cart page, if the client changes his/her mind and removes the recently added product, the Cart page loads and adds it again since "?add-to-cart=25" is on the URL.

My question is is it possible to remove the "?add-to-cart=product-id" part after the redirection to Cart?

  • 1
    Sounds like a caching problem. You should check with your specific plugin's dev/support team for assistance. – WebElaine Sep 27 '17 at 15:43
  • It's not a caching problem. If I go to mydomain.com/cart/ and then refresh the page, there is no problem. But if I got to mydomain.com/cart/?add-to-cart=25 and then refresh the page, the cart will try to add the same product once again - it will add a product on each refresh. It's a problem of keeping the $_GET query variable "add-to-cart" in the URL. – dev_masta Jan 12 '18 at 0:18
1

This is my solution (redirect to the checkout page if the user clicked on a custom add-to-cart button):

function xnagyg_redirect_checkout_add_cart( $url ) {
  //continue only if we found add-to-cart in the URL!!!
  if ( empty( $_GET['add-to-cart'] ) || ! is_numeric( $_GET['add-to-cart'] ) ) {
    return false; //do not redirect
  }
  $url = get_permalink( get_option( 'woocommerce_checkout_page_id' ) ); //Redirect to Checkout page
  return $url;
}

add_filter( 'woocommerce_add_to_cart_redirect', 'xnagyg_redirect_checkout_add_cart' );
0

The solution would be to lose the ?add-to-cart=25part of the URL. The simplest way to do that is with javascript History API:

history.pushState(null, "", location.href.split("?")[0]);

Docs: https://developer.mozilla.org/en-US/docs/Web/API/History_API

The DOM window object provides access to the browser's history through the history object. It exposes useful methods and properties that let you move back and forth through the user's history, as well as -- starting with HTML5 -- manipulate the contents of the history stack.

It was introduced in HTML5 so older browsers might not support it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.