How to Get Logged-in User’s Info in WordPress for Personalized Results

110

Recently we showed you how to create a personalized experience for your users by allowing them save their favorite posts in a personalized library. You can take personalized results to another level by using their first name at places (i.e the welcome screen). Luckily, WordPress makes it really easy to get the logged-in user’s information. In this article we will show you how to retrieve information pertaining to the currently logged in user.

We will utilize get_currentuserinfo(); function. This could be used anywhere in your theme (header, footer, sidebar, page-template etc). In order for this to work the user must be logged-in. So we will need to use the conditional statement is_user_logged_in(). Example code:

<?php if ( is_user_logged_in() ) { ?>      <!-- text that logged in users will see -->  <?php } else {   ?>      <!-- here is a paragraph that is shown to anyone not logged in -->    <p>By <a href="<?php bloginfo('url'); ?>/wp-register.php">registering</a>, you can save your favorite posts for future reference.</p>  <?php } ?>

Now for the logged_in users, we can show a custom message for instance, “Hey Syed, Everything is here, right where you hoped it would be”. The above code will turn into something like this:

<?php if ( is_user_logged_in() ) { ?>      <!-- text that logged in users will see -->    <?php global $current_user; get_currentuserinfo(); ?>    <h1>Hi <?php echo $current_user->user_firstname; ?></h1>    <p>Everything is here, right where you hoped it would be :)</p>    <?php } else {   ?>      <!-- here is a paragraph that is shown to anyone not logged in -->    <p>By <a href="<?php bloginfo('url'); ?>/wp-register.php">registering</a>, you can save your favorite posts for future reference.</p>  <?php } ?>

The magic code that we added above is $current_user->user_firstname; which is working because the call to get_currentuserinfo() places the current user’s info into $current_user. You can use the similar method to get other information about the user such as their login, user ID, email, website etc.

Here is a sample usage of all information:

<?php global $current_user;        get_currentuserinfo();          echo 'Username: ' . $current_user->user_login . " ";        echo 'User email: ' . $current_user->user_email . " ";        echo 'User first name: ' . $current_user->user_firstname . " ";        echo 'User last name: ' . $current_user->user_lastname . " ";        echo 'User display name: ' . $current_user->display_name . " ";        echo 'User ID: ' . $current_user->ID . " ";  ?>

Hope this helps. Combining this with the ability to add favorite posts, you can easily create a personalized experience.