Agnes Pandek
Agnes Pandek

Reputation: 149

Wordpress Woocommerce product is being added to cart on page refresh

I have a problem using woocommerce.

After I add a product to cart the link in browser becomes link/?add-to-cart=72, and if I refresh the page the product is added again in cart.

Every refresh addes the product in cart. I disabled all plugins except woocommerce and still the same.

Any idea on how to fix this? Thank You.

Upvotes: 6

Views: 6813

Answers (3)

Talal Saeed
Talal Saeed

Reputation: 1

add_action('woocommerce_add_to_cart_redirect', 'cipher_add_to_cart_redirect');

function cipher_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;
    }

    // Get the URL of the current product
    if (isset($_REQUEST['add-to-cart'])) {
        $product_id = $_REQUEST['add-to-cart'];
        $product_permalink = get_permalink($product_id);

        // If the product URL is available, redirect to it
        if ($product_permalink) {
            return $product_permalink;
        }
    }

    // If the product URL is not available, redirect to the home page
    return home_url('/');
}

Upvotes: 0

solene_ggd
solene_ggd

Reputation: 21

Thanks for the answer @asfandyar-khan, it works for me.

Just a little update though, add_to_cart_redirect is deprecated since version 3.0.0, we need to use woocommerce_add_to_cart_redirect instead.

Which makes :

add_action('woocommerce_add_to_cart_redirect', 'example_add_to_cart_redirect');

function example_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'));
 
}

Upvotes: 2

Asfandyar Khan
Asfandyar Khan

Reputation: 1738

I had the same issue once, here is 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', 'cipher_add_to_cart_redirect');
 
function cipher_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'));
 
}

It will add a redirection when users added products to their cart. I hope this helps.

Upvotes: 17

Related Questions