How to Display the Avatar for the Currently Logged in User with get_avatar in WordPress

Home » Snippets » How to Display the Avatar for the Currently Logged in User with get_avatar in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you looking to enhance the user experience on your WordPress site by displaying the avatar of the currently logged-in user? The get_avatar function in WordPress makes it incredibly easy to retrieve and display the avatar for any user, but it can be especially useful for displaying the avatar of the user who is currently logged in. In this article, we will guide you step-by-step on how to use the get_avatar function to display the avatar for the currently logged-in user on your WordPress site.

					function wpturbo_display_user_avatar() {
    $user = wp_get_current_user();
    $avatar = get_avatar($user->ID);
    
    echo $avatar;
}
add_action( 'wp', 'wpturbo_display_user_avatar' );
				

The code snippet provided allows you to display the avatar of the currently logged in user on your WordPress website. Let’s break down how it works step by step.

Starting with the function wpturbo_display_user_avatar(), we first retrieve the currently logged in user using wp_get_current_user(). This function returns an object that represents the current user. We assign this object to the variable $user.

Next, we use the get_avatar() function to retrieve the avatar of the current user. The get_avatar() function accepts the user ID as its parameter (in this case, we pass $user->ID), and it returns the HTML for the avatar. We assign this HTML to the variable $avatar.

To display the user’s avatar, we simply echo the $avatar variable using echo $avatar.

The last step is to hook the wpturbo_display_user_avatar() function to the wp action. This ensures that the function is executed when the WordPress main query is run. In other words, the user’s avatar will be displayed on the front-end of your website.

By adding this code to your theme’s functions.php file or a custom plugin, the avatar for the currently logged in user will be automatically displayed wherever you place the function call.

Please note that the appearance and size of the avatar can be customized by passing additional parameters to the get_avatar() function. For example, you can specify the avatar size by appending , array('size' => 100) to the function call.

Register an account to save your snippets or go Pro to get more features.