Get in Touch

Please enable JavaScript in your browser to complete this form.
Email

Using Sessions in WordPress

Time to Read:

1 minute

The WordPress platform is totally stateless and provides no support for the use of sessions outside of the cookie that keeps a user logged in. This is a very good policy and helps keep your blog light and responsive. Unfortunately there are times that a session might be convenient to hold some data between requests.

My goal today is to get you on your way with sessions if you’re building plugins that require sessions, like i did when restricting access to posts based on passwords.

Well if you want the code and be done with it here it is:


add_action('init', 'myStartSession', 1);
function myStartSession() {
if(!session_id()) {
session_start();
}
}

the above code is enough to start a session and set variable according to your hearts merry desires.
Below is a bit of working code for when to unset sessions when logged out


add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myStartSession');

function myStartSession() {
/* this code starts sessions when logging in */
    if(!session_id()) {
        session_start();
    }
}

function myEndSession() {
    session_destroy ();
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Latest Posts

Filter