php, wordpress

Custom random avatars in WordPress

 

When someone places a comment in WordPress, the blog tries to identify them by email. The email address is not shown on the comments, but if they happen to have a Gravatar account, their profile picture from that service will be used.

If a Gravatar is not found for that email, then a default image will be used. WP can be set up to use

  • “Static” default avatars, which are shared between all anonymous commenters, and
  • “Generated” default avatars, which will vary from user to user.

This configuration resides in Settings > Discussion .

You can see the difference between “Generated” and “Static”.

 

 

I wanted something similar to the “Generated” ones, but more personalized.

In order to achieve this, one can modify the behaviour of the function get_avatar(). There is two main ways:

  • You can add a filter to the avatar_defaults  option, and modify the “avatars array” in order to get a new “Static” default avatar option in Discussion Settings. You can see an example here.
  • You can add the filter to pre_option_avatar_default , and return any URL you want.

I will use the second option, so the URL returned will be picked up randomly from a set.

This will modify the regular flow WordPress uses, and return a custom random avatar. I created 14 avatars, named them cham_avatar0.jpg  to cham_avatar13.jpg , and copied them into my wp_admin/images/cham_avatars folder .

The problem is that modifying the source code of WordPress directly is not ideal, because will be messed up in WP updates.

I recommend using the WordPress plugin Code Snippets for this. It helps keep your modifications organized and safe from updates, and you can easily enable or disable them.

So I followed these steps:

  1. installed Code Snippets
  2. downloaded a bunch of Creative Commons chamaeleons that I liked, and cropped them
  3. resized them with for i in *; do convert $i -resize 90x90 $i; done ,
  4. uploaded to my website’s wp-admin/images/cham_avatars/ folder,
  5. pasted the code snippet, and
  6. hit save and enable.

It is really that simple!

Author: nachoparker

Humbly sharing things that I find useful [ github ]

Leave a Reply

Your email address will not be published. Required fields are marked *