Daily Archives

One Article

Online

Using WordPress Sessions Everywhere In PHP

Posted by Jamie Woods on

Like a huge number of sites, Insanity’s website runs off of WordPress.

Although we use custom WordPress plugins all over the place, there’s plenty of traditional PHP dotted around our website (for example, on our listen pages).

There might be times when you need to get access to session data (e.g. to check if someone’s logged in) from outside of WordPress. Why add another login form when you can reuse the session you already have?

You get the point. Let’s get straight into the code.

<?php
define('SHORTINIT', true);
define('ABSPATH', '/path/to/wordpress/');
define('WP_PLUGIN_URL', '');

require_once ABSPATH . 'wp-load.php';
require_once ABSPATH . WPINC . '/link-template.php';

define('SITEROOT', get_site_url() . '/');

require_once ABSPATH . WPINC . '/class-wp-user.php';
require_once ABSPATH . WPINC . '/class-wp-roles.php';
require_once ABSPATH . WPINC . '/class-wp-role.php';
require_once ABSPATH . WPINC . '/class-wp-session-tokens.php';
require_once ABSPATH . WPINC . '/class-wp-user-meta-session-tokens.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';

wp_cookie_constants();

require_once ABSPATH . WPINC . '/vars.php';
require_once ABSPATH . WPINC . '/kses.php';
require_once ABSPATH . WPINC . '/rest-api.php';
require_once ABSPATH . WPINC . '/pluggable.php';
require_once ABSPATH . WPINC . '/general-template.php';

if ( !is_user_logged_in() ) {
        die(header('Location:  ' . wp_login_url(SITEROOT . $_SERVER['REQUEST_URI'])));
}

$wp_user = wp_get_current_user();
// do whatever you want with $wp_user here
?>