How do you use session variables in wordpress?

2019-04-09 13:37发布

I have the following plugin: http://wordpress.org/support/plugin/wp-session-manager

I cannot work out how to use the session variables in WordPress. From what I understand by reading, this is how it should be used:

I have the following on page one (page 1):

global $wp_session;
$wp_session['loggedIn'] = 15;

echo $wp_session['loggedIn'];

On the first page, the session variable is working but on the second page, the session variable is not working. Can anyone suggest me where I am going wrong?

Thanks.

3条回答
放我归山
2楼-- · 2019-04-09 14:14

Introducing WP_Session:

Example :

global $wp_session;

$wp_session['user_name'] = 'User Name'; // A string

$wp_session['user_contact'] = array( 'email' => 'user@name.com' );// An array

$wp_session['user_obj'] = new WP_User( 1 ); // An object

// wordpress session functions :

  1. wp_session_cache_expire() – get the session expiration time
  2. wp_session_commit() – write session data out to the transient
  3. wp_session_decode() – load data into the session from a serialized string
  4. wp_session_encode() – write session data out to a serialized string
  5. wp_session_regenerate_id() – change the ID of the current session to a new, random one
  6. wp_session_start() – start the session and load data based on the user’s cookie
  7. wp_session_status() – check the status of the current session
  8. wp_session_unset() – clear out all variables in the current session
  9. wp_session_write_close() – write session data and end session.
查看更多
时光不老,我们不散
3楼-- · 2019-04-09 14:20

Replace:

global $wp_session;

With:

$wp_session = WP_Session::get_instance();

Make sure you add $wp_session = WP_Session::get_instance(); before you try to echo the variable on page 2.

查看更多
倾城 Initia
4楼-- · 2019-04-09 14:22
  1. Add below code in function.php file
function register_my_session(){
    if( ! session_id() ) {
        session_start();
    }
}

add_action('init', 'register_my_session');
  1. After that you can store value in session variable like
$_SESSION['something'] = $xyz
查看更多
登录 后发表回答