Using Sessions in WordPress themes and Plugins

Posted on Monday, November 12th, 2012

Without hacking core files

WordPress aims to be stateless, so it uses cookies, not sessions.

Which is fine, except for there are things you may need to do that would best be accomplished by tapping into PHP’s sessions.

But, there’s a problem: WordPress iterates over the $_SESSION variable and unsets any session data in wp-settings.php file.

There’s articles out there suggesting editing the wp-settings.php file, but I have a hard and fast rule about not modifying core files for WordPress (or Magento, or Open Cart), because the next time you update your installation (which is important for security), you may wipe your modifications.

There’s a better way.  Why not just hook the session_start AFTER wp-settings.php has run?

Simple as can be with just five lines of code. First, we set up the action to hook into wp-loaded:

add_action('wp_loaded', 'start_my_custom_session');

And then we set our function start_my_custom_session:

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

Leave a Reply

(required)

comment on this post »

No comments on this post yet.