How to use session_start in Wordpress?

2019-01-17 16:07发布

I'm creating a bilingual site and have decided to use session_start to determine the language of the page using the following:

session_start();    
if(!isset($_SESSION['language'])){
    $_SESSION['language'] = 'English'; //default language
}

The problem with this is that it clashes with Wordpress and I get the following:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/neurosur/public_html/v2/wp-content/themes/default/header.php:8) in /home/neurosur/public_html/v2/wp-content/themes/default/region.php on line 13

Is there a way to get around this?

3条回答
做自己的国王
2楼-- · 2019-01-17 16:45

EDIT

Wordpress sends header info before the header.php file is run. So starting the session in the header.php may still conflict with the header info that wordpress sends. Running it on init avoids that problem. (From jammypeach's comment)

Write the following code in your functions.php file:

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

add_action('init', 'register_my_session');

Now if you want to set data in session, do like this

$_SESSION['username'] = 'rafi';
查看更多
仙女界的扛把子
3楼-- · 2019-01-17 16:47

Move your code to the top of header.php file. And check if session already exists:

if(session_id() == '')
     session_start(); 

your code here...
查看更多
smile是对你的礼貌
4楼-- · 2019-01-17 16:56

I found an interesting article by Peter here. I'm using the following code in my functions.php:

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 ();
}

This destroys old session when user logs out then in again with different account.

查看更多
登录 后发表回答