Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use session_start in Wordpress?

Tags:

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?

like image 728
Rob Avatar asked Aug 03 '12 14:08

Rob


People also ask

When should the session_start () function be used?

The session_start() function is used to start a new session or, resume an existing one.

Do I need to call session_start on every page?

It must be on every page you intend to use. The variables contained in the session—such as username and favorite color—are set with $_SESSION, a global variable. In this example, the session_start function is positioned after a non-printing comment but before any HTML.

How do I use session plugins in WordPress?

From your WordPress dashboardVisit 'Plugins > Add New'. Search for 'Sessions'. Click on the 'Install Now' button. Activate Sessions.


1 Answers

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'; 
like image 112
rafi Avatar answered Oct 03 '22 01:10

rafi