How to use my own custom session value in WordPress?

EDIT: “THE PLUGIN BELOW ISN’T AVAILABLE ANYMORE, SO PLEASE USE THAT PLUGIN INSTEAD: WordPress Session Plugin

There is a good WordPress Plugin adapted from CodeIgniter Session class: WP Sessions Plugin.

When you activate the plugin, you can start to use $session object from anywhere in your theme ($session object as long as global). For instance, to use $session object into header.php file, simply add this code:

global $session;

If you are a plugin developer and you want to adapt this plugin with yours, you can find standalone version in the package as well. Documentation of the plugin gives more information for plugin developers about how to adapt to your project.

Here is some useful functions for both theme and plugin developers.

You can add session data like this:

// One value
$session->set_userdata( 'username', 'john' );

// Passing array
$array = array(
    'username' => 'john',
    'email'    => '[email protected]'
);

$session->set_userdata( $array );

To retrieve session data:

$session->userdata( 'username' );

To get all session data:

$session->all_userdata(); // returns array

To remove one item from session:

$session->unset_userdata( 'username' );

To remove more items from session:

$array = array(
    'username' => '',
    'email'    => ''
);
$session->unset_userdata( $array );

You can also use Flashdata which is session data that will only be available for the next server request, are then automatically cleared. These can be very useful when you use them for informational or status messages (e.g. “Product has been deleted”).

// Add Flashdata
$session->set_flashdata( 'item', 'value' );

// Retrieve Flashdata
$session->flashdata( 'item' );

// Preserving flashdata 
// (if you need to preserve flashdata through an additional request, 
// you can use this function):
$session->keep_flashdata( 'item' );

To destroy session:

$session->sess_destroy();

The plugin also supports shortcodes. You can print any session data on your posts or pages:

[session key="username"]

To reach second key:

[session key="user_data" sec_key="display_name"]

I hope this helps for someone.

Leave a Comment