Skip to content

Instantly share code, notes, and snippets.

@bryceadams
Last active October 9, 2023 13:55
Show Gist options
  • Save bryceadams/db6c8669e9e99cb2808c to your computer and use it in GitHub Desktop.
Save bryceadams/db6c8669e9e99cb2808c to your computer and use it in GitHub Desktop.
Clear WooCommerce Cart (when not cart/checkout)
/**
* Clears WC Cart on Page Load
* (Only when not on cart/checkout page)
*/
add_action( 'wp_head', 'bryce_clear_cart' );
function bryce_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 );
}
@RobKuipers
Copy link

Hi Bryce, have been using your snippet happily for some time. But now something has broken it. Haven't figured out what yet. Could be just me (added some plugins, configured some more W3 Total Cache etc.), or it could be the latest Woocommerce. Just so you know; you might want to check your (customers) sites too. Regards, Rob

@indiarocks08
Copy link

Thanks a lot bro ... after going through a lot of solutions .. this worked

@bryceadams
Copy link
Author

@indiarocks08 so happy to hear it! 👍

@indiarocks08
Copy link

can u pls explain this logic :
if ( wc_get_page_id( 'cart' ) == get_the_ID() || wc_get_page_id( 'checkout' ) == get_the_ID() ) {
return;
}

@bryceadams
Copy link
Author

bryceadams commented Oct 8, 2020 via email

@akira22223
Copy link

Sorry, I'm just beginner. Where do I have to insert that code? I am using child theme, so I copied the woocommerce.php file to child theme and inserted that code into that file, but it didn't fix the problem.

@nbhgyhu8ijokmjhbui
Copy link

nbhgyhu8ijokmjhbui commented Jun 10, 2022

Thank you so much!!!
You've been very helpful! I've been looking for this for! Thank you so much!

@joshabar123
Copy link

Just tested and this still works! For anyone who might find this in the future:

Just copy and paste this code to the bottom of your functions.php file. To find this file, go to your web host File Manager then navigate to wp-content > themes > [ choose your current active theme ] > functions.php.

@developmentwitharslan
Copy link

Thanks @bryceadams It still works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment