To check if a user is logged in to WordPress, call is_user_logged_in(). It returns true when the current visitor is signed in and false for everyone else, so you can wrap any PHP in if ( is_user_logged_in() ) { ... } to show, hide, or redirect based on login state.
if ( is_user_logged_in() ) {
echo 'Welcome back!';
} else {
echo 'Please log in.';
}
The function itself is one line. What trips people up is everything around it: when it is safe to call, why it returns false in a REST request or on a cached page, and how to check for an admin the right way. I tested the behavior below on a fresh WordPress 7.1 install in WordPress Playground, logged in as an administrator, as a subscriber, and logged out.
To use these snippets you’ll need to be comfortable with PHP. If you are editing a theme, create a child theme first so your changes survive theme updates, or add the code with a custom plugin or the Code Snippets plugin.
Quick Reference
| You want to | Use | Notes |
|---|---|---|
| Check if anyone is logged in | is_user_logged_in() | Returns true or false |
| Get the logged-in user’s ID | get_current_user_id() | Returns 0 when logged out |
| Get name, email, roles | wp_get_current_user() | Returns a WP_User object (ID 0 when logged out) |
| Check what a user is allowed to do | current_user_can( 'manage_options' ) | Use capabilities, not role names |
| Check for a specific role | in_array( 'editor', wp_get_current_user()->roles, true ) | Only when you really mean the role |
| Force login on a page | auth_redirect() or wp_safe_redirect() + exit | Run on template_redirect |
| Show content to members in a post | A small custom shortcode | Core has no logged-in shortcode |
| Style or script for logged-in users | body.logged-in class | Added by body_class() |
| Check login in a REST request | is_user_logged_in() + an X-WP-Nonce header | No nonce means logged out |
Check if a User is Logged In
Here’s is_user_logged_in() showing a logout link to logged-in users and a login link to everyone else. It works in theme template files (header.php, single.php, a block theme pattern file) and inside any hooked function in functions.php or a plugin.
<?php
if ( is_user_logged_in() ) {
echo 'Welcome back. <a href="' . esc_url( wp_logout_url( home_url() ) ) . '">Log out</a>';
} else {
echo '<a href="' . esc_url( wp_login_url( get_permalink() ) ) . '">Log in</a> to see member content.';
}
Under the hood it is tiny. In core’s wp-includes/pluggable.php it calls wp_get_current_user() and returns $user->exists(), which is true for any user with an ID above zero. Because it lives in pluggable.php, a plugin is allowed to replace it with its own version.
When is_user_logged_in() Is Available (Tested)
You’ll often read that is_user_logged_in() “returns false before init“. That isn’t what happens. WordPress loads pluggable.php right after it includes your active plugins and before it fires plugins_loaded, so from that hook onward the function exists and reads the login cookie correctly. The one place it fails is the top level of a plugin file, where the function has not been defined yet.
I logged in as an administrator, then recorded the return value at each point in the same page load:
| Where the code runs | Logged in as admin | Logged out |
|---|---|---|
| Top level of a plugin file (no hook) | Function not defined yet (fatal error if called) | Same |
plugins_loaded | true | false |
after_setup_theme (and top of a theme’s functions.php) | true | false |
init | true | false |
template_redirect and template files | true | false |
admin-ajax.php (wp_ajax_ action), cookie only | true | false (runs wp_ajax_nopriv_) |
| Custom REST route, cookie but no nonce | false | false |
| Custom REST route, cookie + invalid nonce | 403 rest_cookie_invalid_nonce | n/a |
Custom REST route, cookie + valid X-WP-Nonce | true | n/a |
So the practical rule is: never call it at the top level of a plugin file, and put it inside a hook. init or later is still the safe default, because that is where WordPress itself sets up the current user (WP::init() calls wp_get_current_user() right before the init action fires). If you are new to hooks, my guide to WordPress actions and filters covers how add_action() and priorities work.
In REST API requests
This is the big one. A logged-in browser sends its login cookie with every request, but the REST API ignores that cookie unless the request also carries a nonce. Core’s rest_cookie_check_errors() sees there is no nonce and calls wp_set_current_user( 0 ), so inside your endpoint is_user_logged_in() returns false and get_current_user_id() returns 0. Send a bad nonce and you get a 403 “Cookie check failed” error instead.
The fix is to send the nonce created with wp_create_nonce( 'wp_rest' ) in an X-WP-Nonce header (or a _wpnonce parameter). On your own site the easiest route is wp.apiFetch from the wp-api-fetch script, which adds it for you. External apps should use an Application Password instead of cookies. The WordPress REST API guide walks through each authentication method.
wp_enqueue_script( 'my-script', get_theme_file_uri( 'my-script.js' ), array( 'wp-api-fetch' ), '1.0', true );
// my-script.js
wp.apiFetch( { path: '/myplugin/v1/check' } ).then( ( data ) => console.log( data ) );
For a REST route that should only work for logged-in users, do the check in permission_callback rather than inside the callback:
register_rest_route( 'myplugin/v1', '/profile', array(
'methods' => 'GET',
'callback' => 'myplugin_get_profile',
'permission_callback' => 'is_user_logged_in',
) );
In admin-ajax.php requests
Classic AJAX behaves differently. admin-ajax.php reads the login cookie with no nonce required, and WordPress picks the hook for you: wp_ajax_{action} for logged-in users and wp_ajax_nopriv_{action} for visitors. You still need a nonce check (check_ajax_referer()) before changing anything, but that is for CSRF protection, not for knowing who the user is.
Redirect Logged-Out Visitors to a Login Page
A common use is to lock a page so only logged-in users can see it. Run the check on template_redirect, which fires before any HTML is sent, so the redirect header still works.
Use auth_redirect() to send visitors to the default WordPress login screen and return them to the page afterward:
// Force login on a specific page
add_action( 'template_redirect', function () {
if ( is_page( 'members' ) && ! is_user_logged_in() ) {
auth_redirect(); // sends to wp-login.php, then back here
}
} );
Or use wp_safe_redirect() when you want control over where they land. Always follow it with exit;, otherwise WordPress keeps rendering the page after sending the redirect header:
// Send logged-out visitors to the login page, then back to this page
add_action( 'template_redirect', function () {
if ( is_page( 'members' ) && ! is_user_logged_in() ) {
wp_safe_redirect( wp_login_url( get_permalink() ) );
exit;
}
} );
Logged out, that returned a 302 to wp-login.php?redirect_to=... in my test, and logged in it returned the page with a 200. Swap wp_login_url( get_permalink() ) for home_url( '/login/' ) if you have a custom login page. wp_safe_redirect() only allows your own host (plus anything added with the allowed_redirect_hosts filter). Anything else is replaced with admin_url(), which is why an external login URL silently “doesn’t work”.
Show Content Only to Logged-In Users (Shortcode)
WordPress core doesn’t ship a “members only” shortcode, but it takes a few lines to add one. Wrap any content in [members_only]...[/members_only] and logged-out visitors see a login link instead:
add_shortcode( 'members_only', function ( $atts, $content = '' ) {
if ( is_user_logged_in() ) {
return do_shortcode( $content );
}
return '<p>Please <a href="' . esc_url( wp_login_url( get_permalink() ) ) . '">log in</a> to see this.</p>';
} );
Tested on WordPress 7.1: the admin and subscriber both got the wrapped content, a logged-out request got the login message. The shortcode works in the Shortcode block in the block editor and in classic content. Keep in mind it hides the content in the HTML, so the caching section below applies to it too.
No-code options for block themes
As of WordPress 7.1, core has no block setting for “show only to logged-in users”. If you’d rather not write PHP, two maintained plugins add it:
- Block Visibility by Nick Diego adds a visibility panel to every block, with logged-in, logged-out and user role rules (version 3.8.1, tested up to 7.1.4).
- Content Control restricts whole pages, posts and individual blocks by logged-in status or role, and can redirect people without access (version 2.7.4, tested up to 7.1.4).
Both decide on the server, the same way is_user_logged_in() does, so they need the page cache to bypass logged-in users.
Check if the Current User is an Administrator
To run code only for admins, check a capability with current_user_can(). manage_options (access to the Settings screens) is the standard “is this an admin” check, because out of the box only the Administrator role has it:
if ( current_user_can( 'manage_options' ) ) {
echo 'Only administrators see this.';
}
You will also see current_user_can( 'administrator' ) in a lot of older tutorials, including an earlier version of this one. It does work: WordPress stores a user’s roles in the same array as their individual capabilities, so the role name happens to pass the check. In my test it returned true for the admin and false for the subscriber.
The current_user_can() documentation still calls checking roles in place of capabilities “discouraged as it may produce unreliable results”, and there are concrete reasons:
- A custom role that has
manage_optionsbut is not literally named “administrator” fails the role check. - On multisite, a super admin passes almost any check you give it, so the result doesn’t mean what the code says.
- Plugins that grant capabilities with the
user_has_capfilter work with capability checks, not role names. - Capabilities say what you actually care about (can this person change settings?), which keeps working when someone renames or edits roles.
If you genuinely need the role itself, read it from the user object instead:
$user = wp_get_current_user();
if ( in_array( 'editor', (array) $user->roles, true ) ) {
// The current user has the Editor role.
}
Here’s a capability that separates each default role, taken from the roles WordPress creates on install. A user with a higher role also has the lower roles’ capabilities, so each check means “this role or above”:
| Target | Capability to check | Why this one |
|---|---|---|
| Administrators | manage_options | Only Administrator has it by default |
| Editors and up | edit_others_posts | Authors and Contributors don’t have it |
| Authors and up | publish_posts | Contributors can’t publish |
| Contributors and up | edit_posts | Subscribers can’t write posts |
| Any logged-in user | read or just is_user_logged_in() | Every default role has read |
One correction to the earlier version of this post: edit_posts is not an editor check. Contributors and Authors have it too. Use edit_others_posts for editors. The full breakdown of what each role can do is in my WordPress user roles guide.
Other User Functions Worth Knowing
Depending on what you need, a related function is often a better fit than a plain logged-in check:
get_current_user_id()returns the current user’s ID, or0if nobody is logged in. Handy when you need the ID anyway.wp_get_current_user()returns the fullWP_Userobject, so you can read the user’s display name, email and roles.current_user_can( 'capability' )checks what a user is allowed to do, not just whether they are logged in.is_admin()is not a user check at all. It returns true when the current request is for a wp-admin screen, regardless of who is viewing it.
To show the logged-in user’s profile photo, pass get_current_user_id() to get_avatar().
Being logged in is not the same as being authorized. If an action should be limited to certain roles, check a capability with current_user_can() rather than is_user_logged_in().
Why is_user_logged_in() Returns False When You Don’t Expect It
If the function says a user you know is logged in is a visitor, it’s almost always one of these:
| Symptom | Cause | Fix |
|---|---|---|
| “Call to undefined function is_user_logged_in()” | Called at the top level of a plugin file, before pluggable.php loads | Move it into a hook such as init |
| False inside a custom REST endpoint | No X-WP-Nonce header, so core treats the request as logged out | Send the wp_rest nonce, or use wp.apiFetch |
| Logged-in users see the logged-out version of a page | A page cache served HTML built for a visitor | Bypass the cache when the login cookie is present |
The page cache gotcha
Full-page caches save the HTML that PHP produced and replay it to the next visitor. If a logged-out visit builds the cached copy and a logged-in user is then served that copy, every is_user_logged_in() branch in it is frozen in the logged-out state. The usual defense is to skip the cache whenever the wordpress_logged_in_ cookie is present:
- WP Rocket only caches pages for logged-in users when its User Cache add-on is on, and then it keeps a separate cache per user.
- Cloudflare APO always bypasses its cache for cookies starting with
wp-,wordpressorwpsc_, which covers the login cookie. - A Cloudflare “Cache Everything” rule does not tell logged-in and logged-out visitors apart. Add a cache rule that bypasses cache when
http.cookie contains "wordpress_logged_in_", ordered above the cache-everything rule.
If you need personalized bits on a page that stays cached for everyone, fetch them after the page loads. JavaScript can’t read the login cookie itself, since WordPress sets it as HttpOnly (I confirmed the flag in my test), but an admin-ajax.php request carries the cookie and answers correctly:
add_action( 'wp_ajax_myplugin_status', 'myplugin_status' );
add_action( 'wp_ajax_nopriv_myplugin_status', 'myplugin_status' );
function myplugin_status() {
wp_send_json( array( 'logged_in' => is_user_logged_in() ) );
}
Change Your Site’s Styling for Logged-In Users with CSS
If you don’t need PHP logic, target the logged-in class. Any classic theme that calls body_class() adds it, and block themes get it automatically from core’s template canvas. WordPress adds it to the <body> tag for signed-in users, along with admin-bar when the toolbar is showing.
/* Change the background color for logged-in users */
body.logged-in {
background-color: #bebebe;
}
/* Hide a sign-up box from people who are already members */
body.logged-in .signup-cta {
display: none;
}
The same class works from JavaScript:
if ( document.body.classList.contains( 'logged-in' ) ) {
// The page was rendered for a logged-in user.
}
Treat this as a display hint, not security. The class is written into the HTML by PHP, so it only reflects the real login state when the page wasn’t served from a logged-out cache, and anyone can still read hidden content in the page source. For anything private, check on the server with is_user_logged_in() or current_user_can(). If you’re unsure where your PHP should live, see what belongs in functions.php versus a plugin.
Frequently Asked Questions
What does is_user_logged_in() return?
It returns a boolean: true if the current visitor is logged in to WordPress, false if not. It works by calling wp_get_current_user() and checking whether that user has an ID above zero.
Why does is_user_logged_in() return false in my REST API endpoint?
Cookie authentication in the REST API requires a nonce. Without an X-WP-Nonce header (or _wpnonce parameter) created with wp_create_nonce( ‘wp_rest’ ), WordPress resets the current user to 0, so the function returns false even for a logged-in browser. Use wp.apiFetch on your own site or an Application Password for external apps.
Can I use is_user_logged_in() in a plugin?
Yes, as long as it runs inside a hook. In my test on WordPress 7.1 it returned the correct value from plugins_loaded onward. Calling it at the top level of the plugin file fails because pluggable.php, where the function is defined, has not loaded yet.
How do I check if a user is an admin in WordPress?
Use current_user_can( ‘manage_options’ ). Only the Administrator role has that capability by default. current_user_can( ‘administrator’ ) also works, but WordPress discourages checking role names this way because custom roles, multisite super admins and capability filters can make it unreliable.
How do I show content only to logged-in users without code?
Core WordPress has no logged-in visibility setting for blocks. A plugin such as Block Visibility or Content Control adds logged-in, logged-out and role rules to blocks and pages. Make sure your page cache bypasses logged-in users, or visitors may see a cached version.
Does WordPress add a body class for logged-in users?
Yes. Themes that call body_class() get a logged-in class on the body tag for signed-in users, so you can target body.logged-in in CSS or check document.body.classList in JavaScript.



9 Responses
if( current_user_can('administrator') )is incorrect.
current_user_can checks for a capability, not a role. For example:
if( current_user_can('edit_posts') ) { }if( current_user_can('manage_options') ) { }
Etc
Thanks for the tip, I do agree that targeting a capability may be better but if you export the user’s capabilities using “get_userdata( get_current_user_id() )->allcaps” “administrator” is one of the ones assigned to an admin so the snippet works.
how do i hide a certain page at the top of my header if a user is logged in and show it if they are logged out
You can use the code above in a PHP function to hide anything you want but if you aren’t too familiar with PHP using CSS might be easier. WordPress by default adds a class of “logged-in” to the body of the page so you can target an attribute for hiding using.
body.logged-in .yourclassname {display:none!important};how to check?
if($username != "username"){// my code
}
Let me know if this works
$currentusername = get_user_meta( wp_get_current_user()->ID, 'nickname', true );if($currentusername != "admin"){
echo "You are not Admin";
}
what if the user has logged in and is immediately directed to the landing page? If you haven’t logged in yet, you will be directed to the login page
You could add a conditional statement and use the wp_redirect function to redirect. If your function is before html output it’ll instantly redirect. If it’s after html output (for example in body content of theme html) you can also try a javascript redirect but it’ll have a delay before moving the user. Hope this helps!
here is the gist to adding class into the body tag for login and non login user
https://gist.github.com/raftaar1191/55fe297db0724e62883846b3ed31b543