Warning: Trying to access array offset on value of type bool in /var/www/vhosts/alessandrobuzzi.com/httpdocs/wp-content/plugins/elementor-pro/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /var/www/vhosts/alessandrobuzzi.com/httpdocs/wp-content/plugins/elementor-pro/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /var/www/vhosts/alessandrobuzzi.com/httpdocs/wp-content/plugins/elementor-pro/modules/dynamic-tags/tags/post-featured-image.php on line 39

Warning: Trying to access array offset on value of type bool in /var/www/vhosts/alessandrobuzzi.com/httpdocs/wp-content/plugins/elementor-pro/modules/dynamic-tags/tags/post-featured-image.php on line 39
[t4b-ticker]

How to clear a Woocommerce cart programmatically


Warning: Trying to access array offset on value of type bool in /var/www/vhosts/alessandrobuzzi.com/httpdocs/wp-content/plugins/elementor-pro/modules/dynamic-tags/tags/post-featured-image.php on line 39

A Simple function to clear woocommerce cart after 5 hours

[php]

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 ) {
WC()->cart->empty_cart();
}
}
}

add_action( ‘wp_login’, ‘clear_woocommerce_cart_on_login’ );
<pre>[/php]

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