Search code examples
phpwordpresssession

How to use session_start in Wordpress?


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?


Solution

  • I've changed my original answer to the correct one from @rafi (see below).

    Write the following code in your functions.php file:

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