Home » Incredibly simple WordPress session handler

Incredibly simple WordPress session handler

Here’s a super simple session handler for WordPress. This only initializes the session (starts and stops as needed). You’ll want to add things to the $_SESSION array to your liking. Add this to functions.php:

As you can see, this has ZERO bells or whistles and is intended for the programmer to use sessions as they normally would while automatically destroying and starting the session based on the appropriate login and logout actions of WordPress. You’ll probably want to change this (delete the init action) if you want the session to only be started for logged in users, otherwise this will start a session for every user that hits your site.

Although the above code would work fine for something like a custom shopping cart, you could alternatively only start the session for anonymous (not logged in) users by deleting the init action above and only starting the session when you need to use it. Something like a function that fires when you click “Add to Cart” that checks to see if a session exists and start it if it doesn’t would be a less wasteful approach to starting sessions since they would only start as they are needed.

If you have questions on how to tailor this to your specific needs, feel free to comment!

Leave a Reply

Your email address will not be published. Required fields are marked *