25% off ProSNIPC25OFF

Add an Empty Cart Button

Adds a nonce-protected 'Empty Cart' button to the WooCommerce cart page so customers can clear all items in one click.

PHPby SnipCraft
php
<?php
if ( ! class_exists( 'WooCommerce' ) ) {
    return;
}

add_action( 'woocommerce_after_cart_table', 'scseed_empty_cart_button' );
function scseed_empty_cart_button() {
    $url = add_query_arg(
        array(
            'scseed_action' => 'empty_cart',
            '_wpnonce'      => wp_create_nonce( 'scseed_empty_cart' ),
        ),
        wc_get_cart_url()
    );
    echo '<p class="scseed-empty-cart-wrap" style="margin-top:1em;">'
        . '<a href="' . esc_url( $url ) . '" class="button scseed-empty-cart">'
        . esc_html__( 'Empty Cart', 'scseed' )
        . '</a></p>';
}

add_action( 'template_redirect', 'scseed_handle_empty_cart' );
function scseed_handle_empty_cart() {
    if ( empty( $_GET['scseed_action'] ) || 'empty_cart' !== $_GET['scseed_action'] ) {
        return;
    }
    if ( empty( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'scseed_empty_cart' ) ) {
        wp_die( esc_html__( 'Security check failed.', 'scseed' ) );
    }
    WC()->cart->empty_cart();
    wc_add_notice( esc_html__( 'Your cart has been emptied.', 'scseed' ), 'success' );
    wp_safe_redirect( wc_get_cart_url() );
    exit;
}
#buttons#cart#frontend#ux#woocommerce