Store own custom session value in wordpress

WordPress is not just my favorite CMS but also it attracts a huge number of the developer to work with it. Today, I am sharing a tip that “How to use my own custom session value in WordPress?”

Though it will work but it is not an efficient way to start a session in WordPress. We are going to add all the code to the very top of the theme or you can add this into your theme’s functions.php file.

First, we will add an action that will call a function session_register using the init action which is provided by WordPress.

add_action('init', 'session_register', 1);

Now we will create a function session_register. This function will check the registered session before registering a new session, using PHP function session_id.

function register_session() {
    if (!session_id())

Now $_SESSION will allow you to store data. For example, if you want to store your products in your cart

$_SESSION['cart'] = array(
        'product_id' => 12,
        'quantity' => 2
        'product_id' => 34,
        'quantity' => 1

Or if you want to get data from the session

$cart_products = ! empty( $_SESSION['cart'] ) ? $_SESSION['cart'] : false;

Bansal Sumit

To seek challenging roles and to achieve excellence in the field of Open Source Web Technology with a profound spirit of commitment and dedication.

You may also like...

Leave a Reply

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