WordPress How to set SESSION Custom Variable While Login

Hello friends,

Sometimes we need to set custom session variable for using in our custom code or any other web application which also running parallely with our wordpress installation. Also some time there is need to set and destroy our session variable for our custom web application when wordpress user login or logout.

So first of all we need to enable session in wordpress. I have tested this code in wordpress 3.X. First we need to start the session every time wordpress initialize. To initialize session in wordpress we can use below code.

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

This will start the session every time wordpress loads. In this function you can write any other session variable that you need to set default. Then we also need to destroy the session when wordpress user logout. To destroy the session and unset any variable we can use below code:

add_action('wp_logout', 'session_logout');
function session_logout() {
	session_destroy();
}

In this function you can write any other session variable that you want to unset.

Now, How can we set user data into the session variable? Answer is very simple see the below code:

add_filter('authenticate', 'check_login', 10, 3);
function check_login($user, $username, $password) {
     $user = get_user_by('login', $username);
     $_SESSION['userdata']=$user; return $user;
}

Here we add authentication filter of wordpress to set the session. Also we can use this authenticate filter to restrict certain user from login into the wordpress. This function will set the session and later we can use it any where in the wordpress. Also you can set other system session variable so that when any user logs in wordpress he also get logs in other Custom system but condition is both wordpress installation and custom system need to be on same server.

Please post your comment here if this information helps you. I will keep posting more as I come to know more things.

Thank you 🙂