Search code examples
phpwordpressdatetimewoocommercecart

Empty user's cart without logging them out, after 72 hours in WooCommerce


I am trying to programmatically empty a user's cart after 72 hours of non-activity. Is there a way to find out when a cart was last updated?

I tried to pull a dump of the cart variable, but I could not find a timestamp anywhere indicating the last time a user added something in there.

Not wanting to use a plugin for this please!


Solution

  • The following code below will set a timestamp as custom cart item data each time a product is added to cart:

    // Set current date time as custom item data
    add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data_timestamp', 10, 3 );
    function add_cart_item_data_timestamp( $cart_item_data, $product_id, $variation_id ) {
        // Set the shop time zone (List of Supported Timezones: https://www.php.net/manual/en/timezones.php)
        date_default_timezone_set( 'Europe/Paris' );
    
        $cart_item_data['timestamp'] = strtotime( date('Y-m-d h:i:s') );
    
        return $cart_item_data;
    }
    

    Then the following hooked function will empty cart, when last added item has been added after 72 hours:

    // Empty cart after 3 days
    add_filter( 'template_redirect', 'empty_cart_after_3_days' );
    function empty_cart_after_3_days(){
        if ( WC()->cart->is_empty() ) return; // Exit
    
        // Set the shop time zone (List of Supported Timezones: https://www.php.net/manual/en/timezones.php)
        date_default_timezone_set( 'Europe/Paris' );
    
        // Set the threshold time in seconds (3 days in seconds)
        $threshold_time  = 3 * 24 * 60 * 60;
        $threshold_time  = 1 * 60 * 60;
    
        $cart_items      = WC()->cart->get_cart(); // get cart items
        $cart_items_keys = array_keys($cart_items); // get cart items keys array
        $last_item       = end($cart_items); // Last cart item
        $last_item_key   = end($cart_items_keys); // Last cart item key
        $now_timestamp   = strtotime( date('Y-m-d h:i:s') ); // Now date time
    
        if( isset($last_item['timestamp']) && ( $now_timestamp - $last_item['timestamp'] ) >= $threshold_time ) {
            WC()->cart->empty_cart(); // Empty cart
        }
    }
    

    Code goes in functions.php file of your active child theme (or active theme). Tested and works.