Earlier this week, I was talking with a friend and fellow developer about how I handle sessions in WordPress. Specifically, we were talking about how we take PHP Sessions and WordPress and make them work together (or how we adapt the former into the latter).
This is occasionally a point of interest for WordPress developers since WordPress, as an application, is stateless.
The neat thing, though, is that it gives us a variety of ways to approach this problem. But we’re not the first (and we definitely won’t be the last) to come across this problem.
PHP Sessions and WordPress
Before looking at how to make PHP Sessions and WordPress play nice together, it’s important to understand that PHP has a session mechanism that’s part of the language, that’s relatively easy to use, and that doesn’t require a lot of additional code with which to work.
All of that stuff is in the manual, but arguably the simplest way the define it is:
Session support in PHP consists of a way to preserve certain data across subsequent accesses.
Even after gaining a basic understanding of how it works, what’s the best way to implement them in WordPress? There are some plugins that are available, though I think some are certainly better than others.
My preferred plugin of choice is developed and maintained by the team at Pantheon.
You can grab it in the WordPress plugin directory or you can follow it on GitHub (which I like).
With all of that said, I’m be remiss if I didn’t provide a reference to Pressjitsu’s write-up on how sessions can impact WordPress performance. I highly recommend reading the entire article for anyone who is about to get started working with PHP Sessions and WordPress.
An excerpt from the article, for example:
So if you’re calling
session_start()early on every single request, best case scenario is your caching solution will simply ignore and never cache these requests. Worst case — it will cache the requests individually, meaning if 1000 visitors opened your home page, you now have 1000 different cached copies of the same page. This can lead to other more valuable cached data being evicted to make room for this nonsense.
Clearly, there’s a lot to consider when working with PHP Sessions and WordPress and though plugins can make it easier, I think it’s still important to understand what exactly you’re getting into whenever you’re working with them.
It’s important to make sure that you’re not just throwing tools at a problem without understanding what you’re doing.
Like the quote above states: You don’t want to have 1000 cached copies of the same page. So if you’re going to be using a plugin and implementing sessions or working alongside the plugin, it helps to have the technical understanding of what you’re doing.
Between the aforementioned plugin and article, I think any WordPress developer would be well-armed to handle an implementation of sessions in WordPress.