WordPress has built-in support for Gravatars, globally recognized avatars. This means if you go to Gravatar.com and associate a picture with your email, any WordPress website you post on can use it.
But some people might not want to use Gravatar. I’m working on a magazine site where some of the authors have created gravatars, but many just want to email their photo to the editor and have her take care of it.
I’ve created a Custom Avatar feature that extends the built-in avatar functions of WordPress. It adds a “Custom Avatar URL” field to the user’s Profile page. If an avatar is provided, it is displayed by the function
get_avatar() rather than the gravatar.
The Genesis theme has a great feature called the Author Box. Instead of me having to rebuild it to show my custom avatar, it just works with this solution since I’m extending the built-in avatar functions, not creating new ones.
Adding Custom Avatar Field
We’re going to create two functions: one that displays the field on the profile, and one that updates the field when you click “Update”.
I’ve added a description on the first function to help the users add the correct size photo. Make sure your users upload a square photo (or else it will be squished) and that is at least as large as the largest use in the site. On this project, the Author Box displays the avatar as a 70px square, and on the homepage it’s a 30px square, so I recommend they upload at least 70×70 photo.
Making it Work
We’ll be able to access the custom avatar using
get_the_author_meta( 'be_custom_avatar' ). Now let’s set up a filter on
get_avatar() that uses the custom avatar, if provided.
get_avatar() function to perform in the following way:
- If there’s a custom avatar, use that.
- If there isn’t a custom avatar, check to see if there’s a gravatar. If there’s a gravatar, use that.
- If there’s neither, display the default.