Skip to content
Advertisement

Woocommerce empty the cart button with warning message

is there a way to add a warning message to let user to confirm before user emptys the cart? I’m using this code for creating a button.

  add_action( 'woocommerce_cart_coupon', 'custom_woocommerce_empty_cart_button' );
    function custom_woocommerce_empty_cart_button() {
        echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Svuota carrello', 'woocommerce' ) . '">' . esc_html( 'Svuota carrello', 'woocommerce' ) . '</a>';
    }
    
    add_action( 'wp_loaded', 'atm_woocommerce_empty_cart_action', 20 );
    function atm_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 );
        }
    }

Advertisement

Answer

You can use the init action hook to check URL query params and based on that empty cart.

Use the woocommerce_cart_coupon hook to add an empty cart button beside apply coupon.

Add little JQuery code to show warning alerts to user confirm before empty the cart. check below code.

// check for empty-cart get param to clear the cart
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
    global $woocommerce;
    if ( isset( $_GET['empty-cart'] ) && $_GET['empty-cart'] == 'yes' ) {
        $woocommerce->cart->empty_cart();
    }
}

add_action( 'woocommerce_cart_coupon', 'woocommerce_empty_cart_button' );
function woocommerce_empty_cart_button() {
    global $woocommerce;
    $cart_url = $woocommerce->cart->get_cart_url();
    echo '<a href="'.$cart_url.'?empty-cart=yes" class="button empty_cart" title="' . esc_attr( 'Empty Cart', 'woocommerce' ) . '">' . esc_html( 'Empty Cart', 'woocommerce' ) . '</a>';
}

function custom_scripts(){
    ?>
    <script type="text/javascript">
        (function($){
            $(document).ready(function(){
                $(document).on('click','.empty_cart',function(e){
                    e.preventDefault();
                    if(confirm('Are you sure want to empty cart?')){
                        var url = $(this).attr('href');
                        window.location = url;
                    }
                });
            });
        })(jQuery);
    </script>
    <?php
}

add_action( 'wp_footer', 'custom_scripts', 10, 1 );

Tested and works.

enter image description here

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