WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress: check if user is logged in

153

Here are some notes and examples of how to check if a user is logged in to WordPress.

Best way to check if user is logged in

WordPress provides a nice template tag for checking if the current user is logged in, is_user_logged_in(). Using it is straightforward:

if (is_user_logged_in()) {
	echo 'Welcome, registered user!';
} else {
	echo 'Welcome, visitor!';
}

Here is another example, where a view-invoice function is provided for logged in users, and visitors not logged in are redirected to the WP Login Page:

if (is_user_logged_in()) {
	example_download_invoice();
	exit;
} else { 
	auth_redirect();
	exit;
}

Checking logged in user based on WP cookie

Here is an example of checking logged in users based on the cookie that WP sets upon user login:

$logged_in = false;
if (count($_COOKIE)) {
	foreach ($_COOKIE as $key => $val) {
		if (preg_match("/wordpress_logged_in/i", $key)) {
			 $logged_in = true;
		} else {
			$logged_in = false;
		}
	}
} else {
	$logged_in = false;
}

Note that this example is meant to illustrate the concept. Make sure you have additional security measures in place as cookies are easily spoofed. I’ve used this technique as-is, however, for non-critical UI/UX functionality. For example, display a welcome panel if the user is logged in. The same logic can also be applied via JavaScript/jQuery.

Check logged in user by role

It’s also possible to check logged in users implicitly, by checking their user role:

<?php global $user_identity, $user_ID;
	if (current_user_can('read')) { ?>

	<!-- user can read (logged in) -->

<?php } else { ?>

	<!-- not logged in -->

<?php } ?>

This is useful because WordPress provides a wealth of roles and capabilities to check. Learn more at the WP Codex.

Related Posts

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!