If you're experienced with programmatically creating pages, you may wish to skip down to the code.

I’ve been working on a project where the requirements simply stated this:

  • If the user has a gravatar, display it
  • Otherwise, give the user the ability to upload a profile image from their computer

The WordPress API offers the get_avatar function for easily retrieving a users gravatar image, but there’s currently no API function that allows us to check if a user has a gravatar.

When it comes to writing helper functions, I try to make sure that the function’s signature reads as closely to English as possible. Of course, it’s still code so there’s only so far we can go, right?

Anyway, in order to check if the current user has a gravatar, I wanted to write a function that read something like this:

if( has_gravatar( wp_current_user()->user_email ) {
	// Display the gravatar
} else {
	// Display the form to upload an image
} // end if/else

Check if a User Has a Gravatar

In order to do this, three things need to happen:

  1. An MD5 hashed version of the email address needs to be passed to the Gravatar API
  2. The headers returned from the URL will need to be read
  3. If a 404 is returned, then the user does not have a gravatar

Based on those requirements, here’s the helper function I wrote to check if a user has a gravatar in WordPress:

/**
 * Checks to see if the specified email address has a Gravatar image.
 *
 * @param	$email_address	The email of the address of the user to check
 * @return			          Whether or not the user has a gravatar
 * @since	1.0
 */
function example_has_gravatar( $email_address ) {

	// Build the Gravatar URL by hasing the email address
	$url = 'http://www.gravatar.com/avatar/' . md5( strtolower( trim ( $email_address ) ) ) . '?d=404';

	// Now check the headers...
	$headers = @get_headers( $url );

	// If 200 is found, the user has a Gravatar; otherwise, they don't.
	return preg_match( '|200|', $headers[0] ) ? true : false;

} // end example_has_gravatar

From here, it can be called almost exactly as defined earlier in the post. The function can actually be simplified a bit, but it would decrease readability. Ultimately, it’s your call.

Just remember to replace example with whatever the name of your theme or plugin is in order to follow WordPress coding standards.