Learning more about sessions I’ve gathered that a session_start() should come directly after <?php per Where exactly do I put a SESSION_START? and I wanted to play around and create a plugin that would add a session_start() to header.php after it’s <?php but after searching I’ve been inclusive with trying to figure out the appropriate procedure to do this.

I did search for session but I’ve seen a variety of Q&As that mostly seem to use:

  • init: Session is not starting
  • wp_head: Hook into wp_head(); in a plugin
  • wp_loaded: Getting headers already sent error from plugin

So when authoring a plugin that relies on session to be added to header.php what is the appropriate hook for adding session_start()?

3 s
3

There is no regular output and hence no header sent before template_redirect on the front end. If you need sessions on the back end too, use the action wp_loaded to cover both.

Example:

add_action( 'template_redirect', function() {

    $status = session_status();

    if ( PHP_SESSION_DISABLED === $status ) {
        // That's why you cannot rely on sessions!
        return;
    }

    if ( PHP_SESSION_NONE === $status ) {
        session_start();
    }

    $_SESSION[ 'foo' ] = 'bar';
});

Keep in mind that using sessions adds a whole set of very complex problems to your code, including security, scalability (load balancers), and following time consuming support issues. I don’t recommend it.

Leave a Reply

Your email address will not be published. Required fields are marked *