2

I have a client that has 5 different gravatar images, and would like them to be randomly used as the thumbnail for people's comments that have no Gravatar. I know how to change the Gravatar to a custom one, but not display one of the five in the set randomly each time. I know it can be done, because Automattic does it, but I don't now where I could get a look at that code.

Does someone smarter than I know how this may be done?

//* Create a custom Gravatar
add_filter( 'avatar_defaults', 'sp_custom_gravatar' );
function sp_custom_gravatar ($avatar) {
    $custom_avatar = get_stylesheet_directory_uri() . '/images/gravatar.png';
    $avatar[$custom_avatar] = "Custom Gravatar";
    return $avatar;
}
1

Have a look at the Codex about "Using Gravatars". There you´ll find a part about "Checking for the Existence of a Gravatar" which works like this:

The trick to do this is to specify "404" as the default. In this case, the gravatar service will return a 404 error if no gravatar exists, instead of returning some default image. A real image will get a 200 code. It is best to check for 200, as some other errors might be returned as well, for other cases.

There is also a code snippet you can use for that check.

Then build something like this for your default avatars in single.php/comments.php or whatever you are using:

$default_avatars = array(
                      'yoururl.com/whatever/static/ava1.jpg',
                      'yoururl.com/whatever/static/ava2.jpg',
                      'yoururl.com/whatever/static/ava3.jpg',
                      'yoururl.com/whatever/static/ava4.jpg',
                      'yoururl.com/whatever/static/ava5.jpg'
                   );
$my_default_avatar_now = array_rand($default_avatars);

echo '<img src="'.$my_default_avatar_now.'" class="avatar" />';

array_rand() seems to not have the best randomness from what you read in the comments on php.net but maybe it´s working fine for you.

This code is untested, so it´s more an explanation of the way you could go then a ready-to-use solution.

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.