Skip to content
Advertisement

Empty cart button on woocommerce cart page does not work properly

I’m using this code to creare a button on my woocommerce cart page (near the update cart button):

add_action( 'woocommerce_cart_actions', 'woocommerce_empty_cart_button' );
function woocommerce_empty_cart_button() {
    echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Empty Cart', 'woocommerce' ) . '">' . esc_html( 'Empty cart', 'woocommerce' ) . '</a>';
    }
    
add_action( 'wp_loaded', 'woocommerce_empty_cart_action', 20 );
function woocommerce_empty_cart_action() {
    if ( isset( $_GET['empty_cart'] ) && 'yes' === esc_html( $_GET['empty_cart'] ) ) {
        WC()->cart->empty_cart();
    
        $referer  = wp_get_referer() ? esc_url( remove_query_arg( 'empty_cart' ) ) : wc_get_cart_url();
        wp_safe_redirect( $referer );
        }
    }

The problem is that it works only by clicking two times. I think that the problem could be that I’m using this link to add a product to the cart:

/cart/?add-to-cart=25366

Any idea how to solve this?

Advertisement

Answer

The problem lies in the line:

$referer  = wp_get_referer() ? esc_url( remove_query_arg( 'empty_cart' ) ) : wc_get_cart_url();

The wp_get_referer() function returns the referer of the current page. Basically the link that took you to the current page.

For more information: https://developer.wordpress.org/reference/functions/wp_get_referer/

If you have previously added a product, after clicking on the Empty cart button you will be redirected to the link to add the product to the cart.

You can solve it like this:

// adds the button to the cart page
add_action( 'woocommerce_cart_actions', 'woocommerce_empty_cart_button' );
function woocommerce_empty_cart_button() {
    echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Empty Cart', 'woocommerce' ) . '">' . esc_html( 'Empty cart', 'woocommerce' ) . '</a>';
}

// empty the cart and refresh the page (redirects to the cart page)
add_action( 'wp_loaded', 'woocommerce_empty_cart_action', 20 );
function woocommerce_empty_cart_action() {
    if ( isset( $_GET['empty_cart'] ) && 'yes' === esc_html( $_GET['empty_cart'] ) ) {
        WC()->cart->empty_cart();
    
        $referer = wc_get_cart_url();
        wp_safe_redirect( $referer );
    }
}

The code has been tested and works. Add it to your active theme’s functions.php.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement