is_user_logged_in(): bool

Determines whether the current visitor is a logged in user.

Description

For more information on this and similar theme functions, check out the Conditional Tags article in the Theme Developer Handbook.

Return

bool True if user is logged in, false if not logged in.

Source

function is_user_logged_in() {
	$user = wp_get_current_user();

	return $user->exists();
}

Changelog

VersionDescription
2.0.0Introduced.

User Contributed Notes

  1. Skip to note 8 content

    Please note that is_user_logged_in is a pluggable function and you could get a fatal error if you call it too early.

    To solve this problem, you can wrap the login check within a function hooked to the init action:

    function example_function()
    {
    	if ( is_user_logged_in() ) 
    	{
    		// code
    	}
    }
    add_action('init', 'example_function');
  2. Skip to note 9 content

    Example: In case somebody want to add login and logout link in the template somewhere.

     		
    <?php if ( is_user_logged_in() ) { ?>
        <a href="<?php echo wp_logout_url(); ?>">Logout</a>
    <?php } else { ?>
        <a href="/wp-login.php" title="Members Area Login" rel="home">Members Area</a>
    <?php } ?>
  3. Skip to note 10 content

    Example: From your functions file, this code displays a personal message for logged in users.

    /**
     * Give a personalized message for logged in users and a generic one 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' );
  4. Skip to note 11 content
    /**
     * Redirect to Home page if user attempts to try go to login if logged in
     * @author Arslan <arslan@wpbrigade.com>
     * @return void
     */
    function redirect_to() {
    	global $pagenow;
    
    	if ( !is_customize_preview() && is_user_logged_in() && 'index.php' !== $pagenow ) {
    		wp_redirect( home_url(), 302 );
    		exit();
    	}
    }
  5. Skip to note 12 content

    This function is more accurate if used at, or after, the ‘template_redirect’ Action. Before that, under unusual circumstances, it will give unexpected results.

    The most common case is for a Site Address (URL) without a “www.” when an http:// request is received with a “www.” specified.

    Background: between the ‘wp’ and ‘template_redirect’ Action, the Rewrite rules are applied for Pretty Permalinks. During this process, $_SERVER[‘SERVER_NAME’] is corrected in the common case listed above by removing “www.”

You must log in before being able to contribute a note or feedback.