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