Using sessions in WordPress

Oct 31 2009

WordPress does not use sessions to hold data. It is a stateless application. This means that if you want to use sessions in your plugins or custom modifications of WordPress, you may need to do a little hack to enable sessions.

Edit your wp-config.php file (located at the root of your blog) and add the following line at the beginning of the file:

session_start();

Now you can use sessions in WordPress. Remember that for most plugins, instead of using sessions to store data you can pass variables in URLs and hidden fields or use cookies, and that is what WordPress encourages.

5 responses so far

  • Yes, I’m surprised that WP doesn’t use sessions either. I actually found that using a hook is much better for plugin and themes so you then don’t have to worry about having the user modify their wp-config.php file.

    Here’s a simple function you can add in your functions.php file that will start a session automatically. Then you don’t need the wp-config.php session_start(); code.

    function cp_admin_init() {
    if (!session_id())
    session_start();
    }

    add_action(‘init’, ‘cp_admin_init’);

    • Klaus says:

      Thanks David,

      I have been battling with sessions for a week now, am so glad i came across your code, it helped alot, am trying to build a member area in my wordpress blog, because there is some information that i want to display only to registered users , so that’s where the sessions come in. please post some links to sites that i can read more about this.

      Otherwise thanks

  • shulato says:

    why they don’t use session? what do they use, cookies?

  • how they know if you are still logged in. using cookies?

  • Great share. Thanks a lot. Really saved my day!!

Leave a Reply