phpwordpress

Can we get only users with Gravatar profile image by db query?


I need to retrieve registered users on my Wordpress website who have a Gravatar profile image. Would that be possible using a Wordpress core function, a custom user query (using WP_User_Query class), or either a plugin?

Here is my unsatisfactory solution:

<?php $args = array( 'role' => 'Subscriber', 'number' => 100 );

// The Query
$user_query = new WP_User_Query( $args );

// User Loop
if ( ! empty( $user_query->get_results() ) ) {
    foreach ( $user_query->get_results() as $user ) {
        echo '<div>'
                        . get_avatar( $user->ID, 64 ) 
                        . '<span>' .$user->display_name . '</span>'
                        . '</div>';
    }
} else {
    echo 'No users found.';
}
?>

I'm not happy with this solution because I can't control the number of resulting users with a Gravatar.

On 100 users queried, a limited amount will be displayed here.

Any potential solution is welcome, thanks.


Solution

  • The way gravatars work, all imaginable users have one. So your query doesn't get a subset of users, it gets them all. The hard way.

    The get_avatar() function spits out an HTML image tag that, when rendered in a browser, will hit https://gravatar.com and retrieve the person's gravatar image based (usually) on an email address. get_avatar() doesn't fail in normal production except for rate limiting. You can't tell there's no gravatar for the person, following this code path, until the browser retrieves a placeholder icon because the email in question doesn't have a gravatar. That's pretty useless for something you want to do on the server.

    From server code you could hit the gravatar.com endpoint and tell it you want "404" when it doesn't have a matching account. Read this. Then your server code can use the "404" responses to mean "no gravatar for that user".

    And gravatar.com has a rate limit. So if you hammer on it from a server you'll get 429ed or throttled. It would be wise for your code to stash each user's gravatar-or-not status in a user_meta field with a timeout (that is, cache it). So gravatar.com doesn't decide your server is attacking it.

    It might be wise to rethink this requirement. It's not as simple to implement as anyone might have hoped.