Getting Gravatars on your Single Posts in WordPress
Gravatars are global recognizable avatars, being avatars hosted at Gravatar.com, a service run by Automattic, creators of WordPress and WordPress.com, these days. Since version 2.5 of WordPress there’s built in support for Gravatars, using a template tag to display the appropriate avatar, or a placeholder. The default WordPress theme, being Kubrick renamed as default, uses it in comments, which is the common usage of gravatars.
However, with the recent redesign of Devlounge, I decided to use gravatars rather than theme-bound avatars for displaying the author’s pretty face. You can’t just pull the gravatar code from comments.php to do that, you need to work a bit with the template tag.
First, to display a gravatar you need to register an e-mail with the Gravatar.com service. There, you connect an avatar with the e-mail address. The key is the e-mail address, that’s important to remember.
Displaying the Gravatar
The code used here on Devlounge, for the avatar on the top of the single post pages, is the following:
<?php echo get_avatar( get_the_author_id(), 40 ); ?>
So what does it mean? The
get_avatar() is the WordPress call the Gravatar functionality. As you can see, I’m using the template tag
get_the_author_id() to fetch the singe post’s author ID, which will tell
get_avatar() what e-mail to use to look for. I could use other template tags to fetch the correct e-mail, but I went with the ID one.
40 is the width and height of the avatar in pixels. 16, 32, 48 or 64 are more common uses, but 40 pixels fits the design for me.
If you wanted to, you could add a path to the default avatar URL, so that not the default one from Gravatar.com is displayed for people not having registered an avatar. In this case, I’m going with the default one because people are used to it, and when they see that a gravatar can be used, they might be more inclined to get one.
For comparison, in the comments the gravatar code looks like this:
<?php echo get_avatar( $comment, $size = '32' ); ?>
$comment calls the comment in question’s author e-mail is used to fetch the appropriate avatar, and that one will be 32×32 pixels in size. As above, I could have added a path to a default avatar.