Display avatar only if it exists

In wordpress, hiding avatar if if doesn’t exists sounds like a good idea but it is hard to implement. I haven’t seen a good solution yet.

The problem is that if you do display the avatar even if the email doesn’t exists, people who don’t know about gravatar will find it confusing because they don’t know how to update their profile. However, if you hid the avatar completely, people who knows about gravatar don’t get to see their nice profile pic. Therefore the best solution is to hid it only if the email doesn’t exists. The tricky part is get_avatar() doesn’t tell you if the user is valid or not. If invalid, it just returns a mystery pic.

I have thought of several solutions. The best solution is probably to download the mystery image and md5 it against the dynamically generated avatar pic. This means I have an extra image to save in my existing installation which I don’t want. There is one more less accurate way of doing it, ie to compare the file size. I have wrote a short snippet here:

function display_avatar_only_if_it_exists($avatar) {
  preg_match("/src='([^']+)\'/", $avatar, $matches);
  $file = file_get_contents($matches[1]);
  // if user is unknown, it will by 2174 bytes
  if (strlen($file) == 2174) {
  else {
    return $avatar;
// do this only in the frontend
if (!is_admin()) {
add_filter('get_avatar',  'display_avatar_only_if_it_exists');

Author: bpeh

Bernard Peh is a great passioner of web technologies and one of the co-founder of Sitecritic.net Website Design and Reviews. He works with experienced web designers and developers everyday, developing and designing commercial websites. He specialises mainly in SEO and PHP programming.