WooCommerce PHP Intermediate Requires WooCommerce

Add an “Empty Cart” Button

Let shoppers clear their whole cart with one click on the cart page, protected by a security check.

Tested on WordPress 7.1 PHP 8.3 Updated
functions.php 19 lines
// Show the button next to "Update cart".
add_action( 'woocommerce_cart_actions', function (): void {
	$url = wp_nonce_url( add_query_arg( 'nahnu-empty-cart', '1', wc_get_cart_url() ), 'nahnu_empty_cart' );
	printf( '<a class="button" href="%s">Empty cart</a>', esc_url( $url ) );
} );

// Empty the cart when the button is clicked.
add_action( 'wp_loaded', function (): void {
	if ( ! isset( $_GET['nahnu-empty-cart'] ) || ! function_exists( 'WC' ) || ! WC()->cart ) {
		return;
	}
	if ( ! wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ?? '' ), 'nahnu_empty_cart' ) ) {
		return;
	}
	WC()->cart->empty_cart();
	wc_add_notice( 'Your cart is now empty.' );
	wp_safe_redirect( wc_get_cart_url() );
	exit;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Removing items one by one is tedious when a cart has many lines, especially on wholesale stores. This snippet adds an Empty cart button to the cart page.

How it works

The button is added on woocommerce_cart_actions, next to the coupon and Update cart controls. Its link carries a nonce, a one-time token, so a link on another site can’t empty someone’s cart.

On wp_loaded, after WooCommerce has loaded the cart, the snippet checks the nonce, empties the cart, shows a notice and redirects back to a clean cart URL.

Things to watch

  • This adds to the classic cart. The block-based Cart doesn’t have the woocommerce_cart_actions hook.
  • Consider a confirmation for large carts. Emptying can’t be undone.

How to test it

Add a few items, open the cart and click Empty cart. The cart should be empty with a “Your cart is now empty” notice.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only