Using Sessions in WordPress

Yesterday, when I was creating a new plugin for my friend Stefan Vervoort, I needed sessions to work. Unfortunately, WordPress doesn’t support them?!

I searched the whole source code of this great piece of blogging software, and not on one single line I found even one session. Also the session_start() function is not called, but I still needed my sessions to work 😕 .

So I started searching Google for a fix of my problem. I found a lot of people asking the same question: “Why do sessions not work in WordPress?” Finally I found a solution to fix this little issue and guess what, it is a simple one.

The Solution

The only thing you have to do is call session_start(); before any output is send to the client. Now you might think: Nice, but what happens when I upgrade my WordPress installation to the latest version? Well, yes, your changes will be lost. That is the reason why we first should think of where to add these changes..

Normally upgrading your installation will replace all files, except one. Yes, it is the wp-config.php file. And even better, there isn’t send any output to a client yet, when this file is loaded.

So, we add the next lines of code to our wp-config.php file:

<?php
/**
 * Enable sessions
 */
if (!session_id()) {
    session_start();
}


And sessions are enabled on your blog!
I think the best place to add these lines is at the top of the config file, so immediately after the php starting tag (<?php).

In your theme/plugin

As a lot of people have suggested in the comments, using the wp-config file might not be the best solution.
Add the next piece of code to your functions.php or plugin file to enable sessions:

<?php
/**
 * init_sessions()
 *
 * @uses session_id()
 * @uses session_start()
 */
function init_sessions()
{
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

I hope this will help you out when facing the same problem.

PHP, WordPress
,