Ad
Woocommerce Cart Session Expiration
How to clear Woocommerce cart after x amount of time. I need to reset the session after 30 minutes (Use case: cart was abandoned).
Tried using Woocommerce Cart Expiration plugin but it does not work for last version of Woocommerce 5.7.1 Woocommerce cart expiration.
Also tried via filter (pasted in functions.php), but it doesn't do the job :
add_filter('wc_session_expiring', 'so_26545001_filter_session_expiring' );
function so_26545001_filter_session_expiring($seconds) {
return 60 * 25; // 25 mins
}
add_filter('wc_session_expiration', 'so_26545001_filter_session_expired' );
function so_26545001_filter_session_expired($seconds) {
return 60 * 30; // 30 mins
}
Ad
Answer
you can try this -
// Start session if not started
add_action('init', 'register_my_session');
function register_my_session(){
if( !session_id() ) {
session_start();
}
}
// Clear cart after 30 minutes
add_action( 'init', 'woocommerce_clear_cart' );
function woocommerce_clear_cart()
{
global $woocommerce;
$current_time = date( 'Y-m-d H:i:s');
$expiry_in_seconds = 1800; // 30 minutes
if (!isset($_SESSION['active_time']))
{
$_SESSION['active_time'] = date('Y-m-d H:i:s');
}
else{
// add 30 minutes
$cart_expiry_time = strtotime($_SESSION['active_time']) + $expiry_in_seconds;
// calculate seconds left
$diff = $cart_expiry_time - strtotime($current_time);
// round to minutes
$remaining_minutes = floor($diff/60);
// if time less than or equal to 1 minutes
if($remaining_minutes<=1)
{
//if (isset($_GET['clear-cart']) && $_GET['clear-cart'] == 1)
{
$woocommerce->cart->empty_cart();
//WC()->session->set('cart', array());
//}
}
}
}
Best Method: You should set up a cron job and run accordingly like every 10 minutes. if you want the same function for cronjob kindly uncomment if condition and increase the remaining time like this:
if($remaining_minutes<=15){
if (isset($_GET['clear-cart']) && $_GET['clear-cart'] == 1) {
$woocommerce->cart->empty_cart();
//WC()->session->set('cart', array());
}
}
and add URL on cronejon like this:
https://example.com?clear-cart=1 // your full site domain with param ?clear-cart=1
Ad
source: stackoverflow.com
Related Questions
- → CORS missmatch because of http
- → Building sitemap for 2 wordpress install under 1 domain
- → How to remove empty elements after class?(jQuery)
- → Get width of an element and apply to another relative to the first one?
- → How to remove caption p class from wordpress?
- → 301 Redirection from no-www to www in wordpress
- → Laravel 5 routing using prefix
- → WordPress - Header position Top, Left &Right
- → how to add rel=nofollow to some specific external links in wordpress
- → octobercms install error: database is not empty?
- → How to edit the index page of wordpress theme?
- → How to select a Post Type (Wordpress) to pass a filter in head?
- → What sort of URL structure should be used to display AMP HTML vs vanilla HTML
Ad