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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…