How to clear a Woocommerce cart programmatically

A Simple function to clear woocommerce cart after 5 hours

function clear_woocommerce_cart_on_login() {
if ( is_user_logged_in() && !WC()->cart->is_empty() ) {
$cart_age = current_time( 'timestamp' ) - WC()->session->get( 'cart_created' );
$hours = floor( $cart_age / ( 60 * 60 ) );

if ( $hours >= 5 ) {

add_action( 'wp_login', 'clear_woocommerce_cart_on_login' );

This function checks if a user is logged in using the is_user_logged_in() function. If the user is logged in and the cart is not empty, we check the age of the cart and clear it if it is older than 5 hours.

The function is now hooked to the wp_login action, which will run only when a user logs in. So the cart will be cleared only when a user logs in, and the cart is older than 5 hours.

Share the Post:

Related Posts