The is_user_logged_in() WordPress PHP function determines whether the current visitor is a logged-in user.
Usage
if (is_user_logged_in()) { // Code for logged-in users } else { // Code for non-logged-in users }
Parameters
- None
More information
See WordPress Developer Resources: is_user_logged_in()
Note
It’s important to use the is_user_logged_in() function at, or after, the template_redirect
action. Before that, under unusual circumstances, it may give unexpected results.
Examples
Display a welcome message based on user status
This example displays a different welcome message depending on whether the user is logged in or not.
if (is_user_logged_in()) { echo 'Welcome, registered user!'; } else { echo 'Welcome, visitor!'; }
Add login and logout links in a template
This example adds login and logout links to the template based on the user’s login status.
if (is_user_logged_in()) { echo '<a href="' . wp_logout_url() . '">Logout</a>'; } else { echo '<a href="/wp-login.php" title="Members Area Login" rel="home">Members Area</a>'; }
Display a personalized message for logged-in users
This example displays a personalized message for logged-in users and a generic message for anonymous visitors.
function wpdocs_personal_message_when_logged_in() { if (is_user_logged_in()) { $current_user = wp_get_current_user(); printf('Personal Message For %s!', esc_html($current_user->user_firstname)); } else { echo('Non-Personalized Message!'); } } add_action('loop_start', 'wpdocs_personal_message_when_logged_in');
Redirect to the homepage if the user is logged in
This example redirects users to the homepage if they attempt to access the login page while already logged in.
function redirect_to() { global $pagenow; if (!is_customize_preview() && is_user_logged_in() && 'index.php' !== $pagenow) { wp_redirect(home_url(), 302); exit(); } }