How to Check if User is Logged In WordPress (PHP Function)

Sometimes you want to add functionality or display something only for logged in users. This is easy using WordPress’ built-in is_user_logged_in() function. This quick tip will show you how to check if a user is logged in WordPress.

To use this you’ll have to be familiar with programming in PHP. If you are editing a theme we recommend creating a child theme first. This will allow you to edit code in your theme without it breaking when the parent theme is updated.

Here’s an example using the is_user_logged_in() function to display a logout link for logged in users and a login link for logged out users.

<?php
if ( is_user_logged_in() ) {
echo 'Welcome, logged in user. <a href="'.wp_logout_url().'">Click here to logout</a>.';
}else{
echo 'Please login by <a href="'.wp_login_url().'">clicking here</a>.'
}

You can use this in your theme’s function.php to add functionality specific to logged-in users. It will also work in your theme’s index.php, archive.php, single.php, etc for all kinds of functionality for logged in users.

Check if Current User is Administrator in WordPress

If you want to add functionality only for logged in admins this can be done with the current_user_can() function. By using current_user_can(‘administrator’) in an if statement it’ll allow you to check if the current user is a site admin.

<?php
if( current_user_can('administrator') ) {
echo 'This will display for WordPress admins only.';
};

In addition to using is_user_logged_in() in your theme and functions.php you can also include this in a custom WordPress plugin for the same effect.

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way.

2 Responses

  1. 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

    1. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.