A new avatar generator for WordPress with get_avatar and Flathash

Brand new avatars for WordPress Gravatar service

April 7, 2017

WordPress get_avatar function allows to use an image from Gravatar service, which hosts only the image of the user, to represent a user, both a commentor or an author, by matching the user email address with the one stored on Gravatar servers. That’s ok and that’s nice.

Gravatar allows also to use an automatically generated profile image for a user which doesn’t match in their servers.
When you configure your WordPress Discussion settings to use a generated icon for users, you’re telling to use get_avatar with a parameter that tells Gravatar service to return a generated pic if user doesn’t match. You can choose between these generated users icons:

gravatar generated user images

The bad thing is that the Wavavatar, Retro icons, Identicon and MonsterId are really awful from a design point of view.
And the WordPress Gravatar system also lacks of some method to change the automatically generated avatar process.

How to add a new generated set of avatars to WordPress

Here is a solution to sobstitute the avatars automatically generated by Gravatar with the simple, flat and clean Flathash avatars.

To perform this task, since it’s not possible to modify how the Gravatar service works, you have to configure it to return a “blank” image when the user icon has not been found on their services:

choose blank to customize gravatar generated image

Then we modify the get_avatar function using the related hook in your functions.php, the function below is similar to the orignal one but adds a data-rel attribute in the image returned tag.
This data-rel attribute contains the URL of the generated image by Flathash service.
This attribute can’t be used directly on PHP side, because at this moment of the process the result of the call to the Gravatar service is not available, so on PHP side we don’t know if the icon of the user exists or not.
We store the Flathash url to use it later on the client side.

add_filter( 'get_avatar','get_flathash_avatar' , 10, 6 );
function get_flathash_avatar($avatar, $author, $size, $default, $alt, $args) {
  // -------------------------------------------
  // handle user passed by email or by id or obj
  if(isset($author->comment_ID)){
    $code = $author->comment_author_email;
  } else {
    if(stristr($author,"@")) $code = $autore;
      else {
        $autore = get_user_by('ID', $author);
        $code =$autore->user_email;
      }
  }
  // use flathash avatar instead of gravatar
  $flatavatar = "http://flathash.com/". md5( strtolower( trim($code)));
 
  return "<img class='avatar' alt=\"".$alt."\" src='".$args['url']."' data-rel='$flatavatar' width='".$size."' />";
}

To use the data-rel attribute we need to check if the browser has loaded a picture of a user or a “blank” image (as checked on the Settings page). We use image size to evaluate if it contains a valid picture or a blank image, a blank image contains a small amount of data. To read the size of an image we create a javascript image object and load the image, then we create a canvas and copy the image loaded into the canvas. Then we convert it to a base64 string and evaluate the length of the string.
If this string is smaller then 500 bytes we assume it’s a blank image. Here is the code to add in the javascript of your theme:

jQuery(document).ready(function($) {

	function changeAvatar(obj) {
		var img = new Image();
		img.crossOrigin = 'Anonymous';
		img.onload = function() {
			var canvas = document.createElement('CANVAS');
			var ctx = canvas.getContext('2d');
			var dataURL;
			canvas.height = this.height;
			canvas.width = this.width;
			ctx.drawImage(this, 0, 0);
			dataURL = canvas.toDataURL();
			if(dataURL.length < 500) {
				obj.attr("src",obj.attr("data-rel"));
			}
		};

		img.src = obj.attr("src");
		if (img.complete || img.complete === undefined) {
			img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
			img.src = obj.attr("src");
		}
	}

	$("img.avatar").each(function(){
		changeAvatar($(this));
	});

});

You can see the result of this process in this site. So, make some comments :-)
Soon I will make a plugin for it. Plugin here!

Author

I'm a software engineer, an everyday web developer and a maker. I usually build sites with PHP, within or without WordPress. I build Internet of Things with Arduino and ESP8266. I'm the founder of Rockit.it and Dailybest.it and I'm actually the Chief Technical Officer of Better Days web agency.

Recommended

3 ways to add author’s image in WordPress

Add author's image in WordPress without a plugin

April 5, 2017

Two post types share the same taxonomy in WordPress

Sharing a WordPress taxonomy between two post types is useful especially if you want to create a relation between different…

November 14, 2019

Modify the language attribute based on category in WordPress

How to modify the language attribute in your Wordpress theme using a specific value

November 7, 2019

WordPress Fatal error: Unknown: Cannot use output buffering in output buffering display handlers in Unknown on line 0

How I've beat the php mysterious fatal error unknown in Wordpress caused by caching plugin WP Fastest Cache

WordPress Gutenberg doesn’t parse Istagram oembed url

Sometimes Instagram embed doesn't work, why?

November 4, 2019

Stop sending email to new user in WordPress admin registration

A code snippet to prevent WordPress to send notification emails when you manually create new users. It uses a pluggable function.

November 1, 2019