WordPress Snippets

Code Snippet

When you place things in a WooCommerce cart and go to the cart page, it is possible to delete the items one by one. But if you have many things in the cart, it would be nice to have a “Clear Cart” button that removes everyone with one click.

PHP

Place the following code anywhere in your child theme’s functions.php document.

Now there will be a “Clear Cart” button next to the “Update Cart” button in your cart.

// add a "clear cart" button to the woocommerce cart page
function add_clear_cart_button() {
    echo '<a href="' . esc_url( add_query_arg( 'clear-cart', 'true' ) ) . '" class="button clear-cart">Clear Cart</a>';
}
add_action('woocommerce_cart_actions', 'add_clear_cart_button');
    
// handle the "clear cart" functionality
function handle_clear_cart() {
    if (isset($_GET['clear-cart']) && $_GET['clear-cart'] == 'true') {
        WC()->cart->empty_cart();
        wp_redirect(wc_get_cart_url());
        exit;
    }
}
add_action('init', 'handle_clear_cart');

Note

All modifications to a theme or plugin should be made by creating a child theme and placing the changes there. Changes made to the parent theme will be overwritten the next time it updates.


WordPress Notes:

  • All modifications to a theme or plugin should be made by creating a child theme and placing the changes there; changes made to the parent theme will be overwritten the next time it updates

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.