Home > Net >  Woocommerce cart session expiration
Woocommerce cart session expiration

Time:10-13

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
}

CodePudding user response:

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

  • Related