2

I am looking for a way to check if the user has the default gravatar.

  • It doesn't work if I use a simple get_avatar( current_user_id() ) === false as the default gravatar is still an avatar so it never returns false;
  • It doesn't work either if I check the get_avatar_data( get_current_user_id() )['found_avatar'] as it returns 1 even with default gravatar.

Do someone has an idea? Thanks for your help!

  • What was your solution to this; mind sharing it? :) – Sally CJ Oct 4 '19 at 7:34
  • 1
    @SallyCJ I ended up using the wp_remote_get solution (see the explanation of Antti below). – Pipo Oct 8 '19 at 8:44
2

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.

| improve this answer | |
  • Thanks Antti, I had the same conclusion and ended up using the wp_remote_get solution too. Thanks for your time. – Pipo Oct 8 '19 at 8:43
  • 1
    Good answer +1. You might improve it a little by using wp_remote_head to save some overhead where a gravatar does exist. No point downloading it as we're only interested in the response code. – Mark Jun 23 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.