Thoughts, stories and ideas for web developers (with a focus on WordPress)

When you're building a WordPress theme, chances are there are some pages you want to lock down so only signed in users (with specific roles) can access them. Luckily, WordPress makes this very easy.

If you just want to lock down a page for everyone until they're logged in, you can simply put this code at the top of the php template file you want to lock down:

if ( !is_user_logged_in() ) {
        auth_redirect();
    }

This code checks if the user is currently logged in. If this isn't the case, the auth_redirect() function will redirect the user to the authentication page (which is /wp-login by default).

Locking down pages for specific user roles

Single role

If you only want users with a specific role (administrators, for example) to be able to access the page, you can use this code:

$user = wp_get_current_user();

if ( in_array( 'administrator', (array) $user->roles ) ) {
    // the current user is an administrator
} else {
	auth_redirect();
}

This code works by going through the array with roles of the current user (a single user can have multiple roles). If the defined role is in the array (by using the PHP function in_array), you know the current user is an administrator.

Multiple roles

If you want to allow access for multiple roles, you can easily change to code to support an array of supported roles.

$user = wp_get_current_user();
$supported_roles = array('administrator', 'author');

if( array_intersect($supported_roles, $user->roles ) ) {  
   // the current user is an administrator or author
}
You’ve successfully subscribed to Teebow Blogs
Welcome back! You’ve successfully signed in.
Great! You’ve successfully signed up.
Success! Your email is updated.
Your link has expired
Success! Check your email for magic link to sign-in.