Out of the box Gravatar

I’ve been playing with Sandbox theme and WordPress Widgets this past week. I kind of like the idea where every customization is done without touching the theme code base. By using the available WordPress API hooks, let’s play with Gravatar.

Get our hands dirty

Below is the same code that I use to add Gravatar here. If you’re going to use it, make sure to deactivate any Gravatar plugin. You can either add it to your theme functions.php or add it as a plugin.

function gravatar($string) {
	global $comment;

	$email = $comment->comment_author_email;
	$size = 32;
	$default = get_template_directory_uri() .'/images/gravatar.png';
	$gravatar = 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&size='.$size.'&default='.urlencode($default);

	if ( get_comment_type() == "comment" ) {
		if ( $comment->comment_author_url ) {
			$pattern = "/(<a(.*?)href='([^']*.)' rel='external nofollow'>(.+?)<\/a>)/ie";
			$replacement = '("<span class=\"vcard\"><img class=\"gravatar photo\" src=\"$gravatar\" alt=\"\" /> <a class=\"url fn n\"\2href=\"\3\" rel=\"external nofollow\" title=\"Visit \4 website\">\4</a></span>")';
		} else {
			$pattern = "/(([^']*.))/ie";
			$replacement = '("<img class=\"gravatar\" src=\"$gravatar\" alt=\"\" /> \2")';
		}
		return preg_replace($pattern, $replacement, $string);
	} else {
		return $string;
	}
}

By using PHP preg_replace, I create a pattern that match the original output of comment_author_link and then hook it with a new replacement using Filters.

if ( !is_admin() )
	add_filter('get_comment_author_link', 'gravatar');

Basically, you don’t have to insert or modify anything to your comments.php template.
The default gravatar image resides inside folder images as gravatar.png. Usually the Gravatar image is placed on the left of comment author name.

Why the hell vcard class doing there?

Some sort of Microformats hCard experiment for comment authors. Works well but at some point it may break certain rules.

Can anyone write a better regular expression for me?

9 Comments

adib.

ok…how about if i just download it as a plugin and activate it..soo are the plugin will worked

Zeo

As far as I know the plugin works. Have you try?

jazzle

Fantastic idea, just a shame that gravatar.com never seems to serve images for me…

jazzle

Just to spite me gravatar worked for me just now when testing your plugin!

adib.

like don’t work.. i’m using k2..errmm..why can it be like yours??

Zeo

K2 don’t need this since there’s already Gravatar code included in comment.php. Just activate the original Gravatar plugin.

jazzle

Oh noes!
I can’t use it with the ‘Recent Comments’ widget as it adds gravatars there too!

Leave a Comment

(required)
(will not be published) (required)