Check If a WordPress User is Logged In

How to Check If a WordPress User is Logged In

in Functions
Google+ LinkedIn

Sometimes you want to show different content within WordPress based on whether a WordPress user is logged in or not. WordPress provides a simple way to perform this check with is_user_logged_in tag. It returns boolean true or false value and with the help of this tag, we can create unique messages for members, add images or links for logged in users only. These are some of simple usage of what can we do with this tag. On complex side, you can conditional display different sidebars, headers, footers, widgets or even you can configure a completely different design for logged in users.

Here is a simple implementation of this conditional tag and a simple example to display different welcome messages based on whether a WordPress user is logged in or not.

// display different welcome message to logged in users 
if ( is_user_logged_in() ) {
    echo 'Welcome, member!';
} else {
    echo 'Welcome, guest!';
}

This is another example, where we are showing a completely different sidebar, sidebar-members.php to logged in users.

// display different sidebar to logged in users 
if ( is_user_logged_in() ) {
    get_sidebar( 'members' );
} else {
    get_sidebar();
}

Now we can go one step further and display different menus to logged in users. Where logged-in and logged-out are menu names containing different menus items for logged in users and guests, respectively.

// display different menu to logged in users 
function wcs_wp_nav_menu( $args = '' ) {
    if( is_user_logged_in() ) { 
        $args['menu'] = 'logged-in';
    } else { 
        $args['menu'] = 'logged-out';
    } 
    return $args;
}
add_filter( 'wp_nav_menu_args', 'wcs_wp_nav_menu' );

Share the love

If you like this snippet, share it with others!

Leave a Reply

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