0

I've read the usage of session() in WordPress from here and here. And I placed the following code into the very starting of my functions.php:

/**
*   ENABLING SESSION TO THE SITE
*   Thanks: Shazzad
*   Source: http://stackoverflow.com/a/16119876/1743124
*/

function register_session() {

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

add_action( 'init', 'register_session' );

But I can't work with session because that code is failing to start the session. Finally I placed only

session_start();

at the very beginning of my functions.php and it's working fine. I'm using WP 3.9.1.

Is there can be anything wrong, if I proceed with my project running the session start barely at the very beginning?

4
  • Basically: wordpress.stackexchange.com/a/105466/21376
    – s_ha_dum
    Commented Jun 10, 2014 at 14:56
  • 1
    Of note some hosts advise PHP sessions are unreliable, e.g. using PHP sessions on WP Engine can lead to problems ( such as users sharing sessions that shouldn't etc ). Perhaps you'd be better off using cookies and user meta
    – Tom J Nowell
    Commented Jan 22, 2015 at 19:09
  • What are you trying to do with the session?
    – STing
    Commented Jan 22, 2015 at 19:10
  • I completed the project that time with the bare session start (session_start();) and did the language switching for the site. On @G.M.'s recommendation I checked any header already sent check, but found no bug; I always keep my WP_DEBUG true when developing but found no bug either. So it's a kind of problematic project that time. BTW it's working fine now with that bare session start and is functioning as per the client's demand. Thanks all of you. Commented Jan 23, 2015 at 9:25

1 Answer 1

-1

No, there's no disadvantage to starting a session directly in your theme's functions.php.

However, it's strange that starting your session on init is not working for you. Could it perhaps be that output is being generated (perhaps a space or a line break) before init? Could you turn WP_DEBUG on and see if any notices or warnings are being shown?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.