How to check if gravatar of user is the default’s one?

I had a look at the avatar related functions/filters WP provides and I don’t think there is a direct way to tell, if the avatar is a real one or the default image as you only have url to work with.

But, I also looked at the Gravatar implementation guide, https://en.gravatar.com/site/implement/images/, which notes that you can set the default image to return a 404 response when no avatar is found.

Building upon that information, I conjured this code example,

add_filter( 'get_avatar', function( $avatar, $id_or_email, $size, $default, $alt, $args ) {
  if ( is_admin() ) {
    return $avatar;
  }
  // Set default response to 404, if no gravatar is found
  $avatar_url = str_replace( 'd=' . $args['default'], 'd=404', $args['url'] );
  // Request the image url
  $response = wp_remote_get( $avatar_url );
  // If there's no avatar, the default will be used, which results in 404 response
  if ( 404 === wp_remote_retrieve_response_code( $response ) ) {
    // Do something
  }
  // Return img html
  return $avatar;
}, 10, 6 );

This might require some fine-tuning, but in this form it gets the job done. I don’t know would this have some negative effect on the site performance. Especially if there’s a great number of avatar urls that need to be checked on a page load… (but perhaps the status check result could be saved to user/comment meta, get ID from $id_or_email, to improve performance, hmm…?)

You could also do the checking on get_avatar_data() filter, I think.

Leave a Comment