How to store or cache custom shopping cart data for every user’s session

Transients can be used but you’d need to make sure they don’t expire earlier than you want.

I answered a similar question with a different goal here, but I’ve tried to keep the slightly different answer below self-contained.

Option 1 – PHP Sessions

I’ve been storing carts within a PHP session which is fine generally but does have a few problems occasionally. So while it works, I’d recommend something more robust.

My plugin code uses a Basket object. On the init action hook I start the PHP session and if there is a serialised Basket object in the session I unserialise it into a global, otherwise I instantiate a new Basket into the global.

On the shutdown hook I serialise my object into the session.

function setup_session() {

    global $Basket;

    session_start();

    if (isset($_SESSION['basket'])) {
        $Basket = unserialize($_SESSION['basket']);
    } else {
        $Basket = new Basket();
    }

    $Basket->do_actions(); 
    // my own hooks to allow me to add housekeeping code without messing with my core codde

}



function save_session() {

    global $Basket;
    if (isset($Basket)) {
        $_SESSION['basket'] = serialize($Basket);
    }

}

add_action( 'init', 'setup_session' );
add_action( 'shutdown', 'save_session' ); // works even when redirecting away from a page

This works well, but on one site I get a few empty basket problems that are probably a clash with session code for a custom login plugin.

Option 2 – Better Sessions

There’s a WP Session framework written by Eric Mann and explained well by Pippin, who uses it in his well known Easy Digital Downloads plugin, here. You use a global $wp_session exactly as you would $_SESSION but there are also helper functions for managing the sessions. This does use WP’s transients for storage, but also properly handles extending the expiration times so that your baskets don’t get cleaned up too early.

I’ll move over to this in my own sites when I’ve had a good look at how it works for myself.

We try not to send you off following other links in answers here, as they may not last, but pulling them both in here would lead to a rather lengthy answer.

Option 3 – User Logins

If you don’t require shoppers to make an account, then this approach isn’t for you unless you want to code for the concept of an anonymous user and then convert their basket to one for a logged in user as they create their account. If you do require user accounts, then this is the way to go as you can hand the session management over to WP’s built in user logins. Then on init & shutdown you can unserialise and serialise your basket into a user meta field, which will persist between login sessions.

While update_user_meta will handle serialisation for you, be aware of this longstanding bug when trying to store an object.

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)