最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

avatar - How to check if gravatar of user is the default's one?

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked Sep 30, 2019 at 9:53 PipoPipo 6092 gold badges11 silver badges27 bronze badges 2
  • What was your solution to this; mind sharing it? :) – Sally CJ Commented Oct 4, 2019 at 7:34
  • 1 @SallyCJ I ended up using the wp_remote_get solution (see the explanation of Antti below). – Pipo Commented Oct 8, 2019 at 8:44
Add a comment  | 

1 Answer 1

Reset to default 5

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/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.

发布评论

评论列表(0)

  1. 暂无评论