skip to Main Content

I’m trying to use this code to redirect to a shop page and clear the cart using clear-cart query string but there is an issue I’m having. When it redirects to the shop page, the cart clears but when I try to "Add to Cart" a new product, it refreshes the page and clears the cart again. This is because the url contains the query string at the end of it now www.my-site.com/shop/?clear-cart. As I would like to have the option to add multiple items to the cart, is there a way that when it redirects it will remove the query string from the url? Or is there a better solution for this?

add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    if ( isset( $_GET['clear-cart'] ) ) {
        global $woocommerce;
        $woocommerce->cart->empty_cart();
    }
}

2

Answers


  1. After you have emptied the Cart you could call the header function.

    header("Location: www.mysite.com/shop");
    
    Login or Signup to reply.
  2. Try the following that uses template_redirect hook to first empty the cart and redirect to shop page (removing the query string):

    add_action( 'template_redirect', 'empty_cart_and_redirect' );
    function empty_cart_and_redirect( $query ) {
        if ( isset( $_GET['clear-cart'] ) ) {
            // 1. Empty cart
            WC()->cart->empty_cart();
            
            // 2. Redirect to Shop page
            $redirect_url = wc_get_page_permalink( 'shop' );
            wp_redirect( $redirect_url );
            exit();
        }
    }
    

    Code goes in function.php file of your active child theme (active theme). It should work.


    to redirect to corner-store, try to use instead:

    $redirect_url = home_url( '/corner-store/' );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search