Displaying user avatars using get-avatar in WordPress
1 min read

Displaying user avatars using get-avatar in WordPress

Avatar is an important component of WordPress, and whether you are developing themes or custom features, we will introduce all the methods to obtain user avatars in WordPress in this article.

Normally, avatars in WordPress display Gravatar, but all of the following features can be replaced by plugins in WordPress.

How to display the profile picture of the current logged in user

In WordPress, using get_avatar() makes it easy to obtain the profile picture of the currently logged in user. Through this function, you can input the user ID, avatar size, and output image labels with the correct avatar.

I also provided a code snippet using get_avatar_url(), which allows you to directly retrieve the URL of the user profile picture and use it in any way you want.

<?php
// Ensure user is logged in
if( is_user_logged_in() ) {
 // Display current logged in user's avatar (includes <img> tag)
 echo get_avatar( get_current_user_id(), 96 );

 // Display current logged in user's avatar URL
 echo get_avatar_url( get_current_user_id(), array( 'size' => 96 ) );
}

You can use the above code snippet for any custom features on the WordPress website. For example, in a custom theme, add the login user’s profile picture to the header.

In the example function above, I also specified the size of the avatar to be 96. You can replace “96” with the height/width of the avatar you want. If the resolution is high, 512 can be used, and if the resolution is low, 32 can be used.

How to display the profile picture of the current article author

You can also easily obtain the avatar of any user ID by using get_avatar and get_avatar_url functions mentioned above. This makes it easy to display the author’s profile picture of the current article.

By using the get_the_author_meta() function, we can obtain the author ID of the current article and use it in the function that displays the author’s profile picture of the current article.

<?php
// Display current post's author avatar (includes <img> tag)
echo get_avatar( get_the_author_meta( 'ID' ), 96 );

// Display current post's author avatar URL
echo get_avatar_url( get_the_author_meta( 'ID' ), array( 'size' => 96 ) );

Of course, you must use this code in the loop. In most cases, it works properly when used in themes or functions.

I hope this article is helpful for you to understand how to use get_avatar in WordPress development. If you have any questions about WordPress development or WordPress code snippets, please let me know in the comments below.