It is surprising that WordPress doesn’t use Sessions for storing data. It is a stateless application. So that if you want to use sessions in your custom modifications or plugins of WordPress, you just need to follow the below ideas!
Idea 1:
Go to the root of your blog (where WordPress is installed). Normally upgrading your WordPress installation will replace all files, except wp-config.php. Edit wp-config.php file and add the following line at the beginning of the file:
// call to sessions in WordPress.
>if (!session_id())
session_start();
Now you can use sessions in WordPress. For most plugins, you can pass variables in URLs and hidden fields or use cookies, instead of using sessions to store data in WordPress.
Idea 2 :
Here is 2nd idea to use sessions in WordPress. Using the below hook is much better for plugin and themes so you don’t need to worry about hacking the root files or modify wp-config.php file. A simple function you can add in your functions.php file, which will start a session by itself. If you use this, then you don’t need the above session_start(); code.
function cp_admin_init() {
if (!session_id())
session_start();
}
add_action(‘init’, ‘cp_admin_init’);
Idea 3 :
If both the above codes are not working for you, here is the 3rd idea. Enter these codes in functions.php
function login_to_wp($u_name){
require(‘wp-blog-header.php’);
$user_login = $u_name;
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action(‘wp_login’, $user_login);
}
function logout_to_wp($u_name){
require(‘wp-blog-header.php’);
$user_login = $u_name;
$user = get_userdatabylogin($user_login);
$user_id = $user->ID;
wp_set_current_user($user_id, $user_login);
wp_set_auth_cookie($user_id);
do_action(‘wp_logout’, ”);
}
login_to_wp($u_name);
}else{
logout_to_wp(”);
}
If your server is currently running register_globals on, you should modify a function named wp_unregister_GLOBALS , which can be found in your wp-settings.php file located in the root directory (where wp-cofig.php file located). To allow sessions you simply have to insert _SESSION into the array for the code, which is located around line 39:
$noUnset = array(‘GLOBALS’, ‘_GET’, ‘_POST’, ‘_COOKIE’, ‘_REQUEST’, ‘_SERVER’, ‘_ENV’, ‘_FILES’, ‘table_prefix’);
Then the final code will look like below:
$noUnset = array(‘_SESSION’,'GLOBALS’, ‘_GET’, ‘_POST’, ‘_COOKIE’, ‘_REQUEST’, ‘_SERVER’, ‘_ENV’, ‘_FILES’, ‘table_prefix’);
Hope this will solve your sessions problem in WordPress.
Guest Writer : Musthafa Ullal has a MCSE 2000 & 2003 with specialization in Messaging, Technology Geek and founder – blogger in TekNoise.com. Visit TekNoise Blog here.
I hope that it should be work well. so, i would like to say thanks for Musthafa for given wonderful info on here 🙂
Thank you Kavya
I think WP reset session variables every times the page loaded.