I am wondering how you can clear the contents of your cart on page load using woocommerce.
I came accross how to add a clear cart button using by adding this in to f
For triggering only on front page your function needs to look like this:
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if ( is_front_page() && isset( $_GET['empty-cart'] ) ) {
$woocommerce->cart->empty_cart();
}
}
function is_front_page() returns true only on front page of your wordpress site. Also, you might detect any other page with function is_page() where you can pass any page title, ID or slug
None of the codes above works on my website. I test it in the latest WordPress version 5.4.1 and the below function works perfectly!
/**
Clears WC Cart on Page Load
(Only when not on cart/checkout page)
*/
add_action( 'wp_head', 'wc_clear_cart' );
function wc_clear_cart() {
if ( wc_get_page_id( 'cart' ) == get_the_ID() || wc_get_page_id( 'checkout' ) == get_the_ID() ) {
return;
}
WC()->cart->empty_cart( true );
}
Try this. I hope it will help you.
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if (strpos($_SERVER['REQUEST_URI'], '/checkout') < 0 )
{
$woocommerce->cart->empty_cart();
}
}
If you need empty cart button on cart page you can use below plugin to clear cart
Plugin Name: Empty Cart Button for WooCommerce Link : https://wordpress.org/plugins/woo-empty-cart-button/
No settings needed just activate plugin.
the above didnt worked for me so i needed something that dont relies on WordPress conditional:
/*empty cart if user come to homepage*/
add_action( 'init', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
if ($_SERVER['REQUEST_URI'] === '/') {
$woocommerce->cart->empty_cart();
}
}
None of the above codes worked on my Wordpress installation (4.9.6). So, I changed the add_action and removed the variable request and went directly to run.
Now my Woocommerce plugin clears products to cart once user exits checkout page without any duplicate errors. Thank you everyone for your help
add_action( 'woocommerce_add_cart_item_data', 'woocommerce_clear_cart_url' );
function woocommerce_clear_cart_url() {
global $woocommerce;
$woocommerce->cart->empty_cart();
}