How to Use Custom Gravatars Icons in WordPressHow to customise the default Gravatars in Wordpress 2.7 using built in WordPress filters to show your own set of custom gravatars images.
When Gravatar support was added to WordPress the default "mystery man" was the only graphic available unless the commenter had previously signed up for Gravatar. Soon after that, there was an option to specify a default image, followed by the Identicon, Wavatar and MonsterID. In WordPress 2.7, the new comments overhaul does not allow custom Gravatars to be defined, since they are all wrapped up into wp_list_comments
.
Let's look at the original method for showing Gravatars:
if(function_exists('get_avatar'))
{
echo get_avatar($comment, $size = '32', $default = get_bloginfo('template_directory') . '/images/gravatar.png');
}
This was a nice simple template function where you pass in the comment (from within the loop), the size for the avatar in pixels, and a filename for the default image.
Since we can no longer make a direct call to get_avatar, we must use a different approach. Thankfully the good guys at WordPress made a nice filter that we can hook into.
function addgravatar($avatar_defaults)
{
$avatar = get_bloginfo('template_directory') . '/images/gravatar.png';
$avatar_defaults[$avatar] = 'Tutorial Gravatar';
return $avatar_defaults;
}
add_filter('avatar_defaults', 'addgravatar');
The filter is called avatar_defaults
and can be used to add a new filename to the array of available filenames. This example assumes that the image is called gravatar.png and is located inside the images folder of your current theme. If this isn't the case you can simply amend the filename. We also need to give the avatar a name; in this case, I called it "Your Paranormal" as this is the site I am writing it for. The last line adds the new function to the filters list.
Now when you go into the WordPress administration screen under Discussion you will see your new default avatar listed and it will be selectable.
There, isn't that nicer than a hard-coded hack in the theme?