Display a User’s Avatar in WordPress with get_avatar

Avatars are an important part of WordPress, no matter if you’re developing a theme or just custom functionality in this post we’ll go over all the ways to get a user’s avatar in WordPress.

Typically in WordPress the avatar will display a Gravatar but all of the functions below should work with plugins that replace Gravatar’s functionality in WordPress.

How to Display Avatar for Currently Logged in User

Getting the current logged in user’s avatar in WordPress is easy with get_avatar(). This function allows you to input a user ID, avatar size and output an image tag with the correct avatar.

I’ve also included a code snippet using get_avatar_url() which allows you to just retrieve the user’s avatar URL to be used in any way you’d like.

<?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 code snippet above for any custom functions on your WordPress site. For example adding the logged in user avatar to the header in a custom theme.

In my example function above I am also specifying the size of the avatar as 96. You can replace “96” with the height/width of the avatar you’d like. For a higher-resolution you could do 512 or for a lower-resolution avatar use 32.

How to Display the Avatar for the Current Post Author

You can also get the avatar for any user ID easily using the get_avatar and get_avatar_url functions mentioned above. This makes it easy for displaying the current post’s author avatar.

Using the get_the_author_meta() function we can grab the current post’s author ID to be used in our function to display the current post author avatar.

<?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’ll have to use this code snippet inside the loop. Most likely where you’re using it in your theme or function it’ll likely work correctly.


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

Andy Feliciotti

Andy Feliciotti

Andy has been a full time WordPress developer for over 10 years. Through his years of experience has built 100s of sites and learned plenty of tricks along the way.

Leave a Reply

Your email address will not be published.

WordPress Tips Monthly

Get the latest from SmartWP to your inbox.