[Wordpress] The get_avatar hook

The problem was how to change the avatars in Wordpress comments for certain comments! I wanted to show avatars from Flickr for comments which my Flickr comment importer plugin gets into a post.

Searching the Wordpress codex hinted at a hook called get_avatar but it was not very well documented. This post is the result of my investigations for being able to use this hook.

The function you hook into get_avatar will receive 3 params so the function you write will be something like

PHP:
  1. function myfunky_get_avatar($avatar, $comment, $size)  {
  2.  
  3. //All your code goes here
  4.  
  5. return $avatar;
  6.  
  7. }

Let me explain the params one by one

  1. $avatar - This is a string which is HTML for the img tag of the Avatar, will be more clear in the example below..
  2. $comment - This is the Wordpress Comment Object, this object has all the details of the comment being currently processed, so you may want to explore the object (Hint: var_dump() is your friend)
  3. $size - This is an integer representing in pixels the size of the Avatar

If you read the above snippet carefully you would have noticed that the function returns $avatar - This usually would be the the img tag modified as per the logic of your code. A piece of working code is worth a thousand words so I will directly skip the words! Here is the function which I have used.

PHP:
  1. function get_flickr_avatar($avatar, $comment, $size) {
  2. //The comments from Flickr have email as nobody@flickr.com
  3. if($comment->comment_author_email == 'nobody@flickr.com'){
  4. $tmp = explode("++",$comment->comment_author_IP);
  5. // Create the new Img Tag
  6. $avatar = "<img class="avatar avatar-{$size} photo" src="http://static.flickr.com/{$tmp[0]}/buddyicons/{$tmp[1]}.jpg" alt="" width="{$size}" height="{$size}" />";
  7. }
  8. return $avatar;
  9. }

And how it the function hooked to the get_avatar hook in the plugin? Just one line

PHP:
  1. add_filter( 'get_avatar','get_flickr_avatar', 1, 3 );

Feel free to add/comment or generally crib about the post


About this entry