By default, WooCommerce only lets users clear items from their cart one by one. This guide shows you how to create one button shown on the cart page which will empty the entire cart in one click. A lot of guides on this topic are using a hook which displays the button next to the coupon field but many store owners don’t have coupons enabled meaning the button does not display. This guide uses the woocommerce_cart_actions hook to display the Empty Cart button next to the Update Cart button.
/**
* Snippet Name: WooCommerce Empty Cart Button
* Snippet Author: ecommercehints.com
*/
add_action( 'woocommerce_cart_actions', 'ecommercehints_empty_cart_button' ); // Create the button
function ecommercehints_empty_cart_button() {
echo '' . esc_html( 'Empty Cart', 'woocommerce' ) . '';
}
add_action( 'wp_loaded', 'ecommercehints_empty_cart_button_empty_cart_action', 20 ); // EMpty the cart if empty button is clicked
function ecommercehints_empty_cart_button_empty_cart_action() {
if ( isset( $_GET['empty_cart'] ) && 'true' === 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);
}
}