Svetlozar
Svetlozar

Reputation: 987

What is the proper way to start session in wordpress?

I'm trying with wp_set_auth_cookie(), but $_SESSION is always empty. What is the proper way to start a session and access the global array $_SESSION in WordPress?

Upvotes: 2

Views: 7639

Answers (3)

Nikunj Gondaliya
Nikunj Gondaliya

Reputation: 344

You have to use this code in function.php

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

Upvotes: 3

Harshal Shah
Harshal Shah

Reputation: 427

This results in the following code to start and destroy the session:

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

function myStartSession() {
    if(!session_id()) {
        session_start();
    }
}

function myEndSession() {
    session_destroy ();
}

To save some data into the session

$_SESSION['myKey'] = "Some data I need later";
And to get that data out at a later time

if(isset($_SESSION['myKey'])) {
    $value = $_SESSION['myKey'];
} else {
    $value = '';
}

Upvotes: 0

sunny bhadania
sunny bhadania

Reputation: 423

If done correctly your functions.php file should now look like this at the top.

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

function start_session() {
    if(!session_id()) {
        session_start();
    }

    add_action('wp_logout', 'end_session');
    add_action('wp_login', 'end_session');
    add_action('end_session_action', 'end_session');

    function end_session() {
        session_destroy ();
    }
}

You can now add data to the global $_SESSION variable that will be accessible at any point within the application during a user session by accessing the $_SESSION variable. The variable is an array; below is an example of adding data to the session array.

$foo = 'Foo Data';
$_SESSION['foo'] = $foo;

Upvotes: 2

Related Questions