How to Create WooCommerce Clear Cart Button Shortcode

WooCommerce clear cart button shortcodeIn this post, I want to demonstrate how you can create WooCommerce clear cart button shortcode and add it to your page template using the do_shortcode function on any place you want to display the WooCommerce clear cart button.

You can use a plugin since there are plugins available to add a clear cart button in WooCommerce but if you do not like using a plugin, you can use the code snippet I will share in this post.

WooCommerce Clear Cart Button

The first step is to create the function that checks if the cart is empty and  this can be achieved by adding the following code snippet in your functions.php file of the child theme.

[php] function njengah_woocommerce_clear_cart_shortcode() {

global $woocommerce;

if ( isset( $_GET[’empty-cart’] ) ) {
$woocommerce->cart->empty_cart();
}
}

add_action( ‘init’, ‘njengah_woocommerce_clear_cart_shortcode’ );

[/php]

Create WooCommerce Clear Cart Button Shortcode

The second step is to create the shortcode that we will use to display the button. The following code snippet when added to your functions.php file or plugin files will help you create the shortcode.

[php]

add_shortcode( ‘njengah_clear_cart’, ‘njengah_clear_cart_button_callback’ );

function njengah_clear_cart_button_callback(){

return'<a class="clear-cart-button" href="<?php echo $woocommerce->cart->get_cart_url(); ?>?empty-cart">

<?php _e( "Clear Cart", "text-domain" ); ?>’;

</a>
}

[/php]

You can now apply the shortcode in your template to display the WooCommerce clear cart button using the shortcode on any template in your WooCommerce site.

Conclusion

In this post we have highlighted the two steps you can use to add WooCommerce clear cart button to your WooCommerce page templates without using a plugin. You can use the code snippets shared above to create WooCommerce clear cart button shortcode that you can add to the page templates or normal posts and pages.

Similar Articles