How To: Add Gravatar support to your WordPress comments

June 18th, 2010

I’m tinkering the whole morning with a WordPress theme and I’m trying to customize it. I made also a separate subdomain in order to play, edit and test themes and WordPress hacks. So, unfortunately this WordPress theme had not Gravatar support out-of-the-box. Therefore, I searched and found a very simple way to implement Gravatar to your WordPress comments.

In fact, it’s piece of cake. You don’t have to know anything about PHP or CSS.

Step 1: your Comments loop

Every WordPress theme supports comments. That equals to a comments.php file in your theme directory. Open it and find the the foreach and endforeach loop (it might look something like this:

<?php foreach ($comments as $comment) : ?> and <?php endforeach; /* end for each comment */ ?>.)

Now, place this code everywhere inside this loop:

<?php if(function_exists('get_avatar')) { echo get_avatar($comment, '50'); } ?>

The “50” string or whatever in this code is your Gravatar’s photo size. You can edit it so it suits your theme’s design or your own likes.

Step 2: Style the Gravatar

By now, Gravatars won’t be styled (left, right, padding, etc). We will do it with a simple CSS code snippet. You probably have noticed that the Gravatar code spits out the “avatar” class on each image. Why not tell now the CSS to float the image left and add a small right margin. Open your style.css file of your WordPress theme and add this line of code:

img.avatar {float:left; margin-right:5px;}

This is it!

There you go! Simple and efficient Gravatar implementation to your WordPress comments. Of course themes will differ, you can style them however you like using CSS. (Hint: this code will only work on WordPress 2.5 and above; but I assume everyone now uses at least 2.9.2 so it won’t be a problem.)

More info about Using Gravatars at the WordPress Codex.

Having problems? Do you want to suggest a different workaround? Feel free to comment.

Comments

  1. A piece of advice would be while you explore the wonders of WordPress make sure you fully understand each function and why it works the way it works.

    It’ ll keep you away from hair pulling session coz there are things in WordPress that act a bit differently and that depends on the place you put your code.

    E.g. inserting the gravatar is a “side effect free” procedure and there’s nothing more to know about.

    I’ll be watching this space as you explore, test and share with us your experiments.

    Keep up :)

  2. Exactly. Wherever you put the Gravatar code (inside the comments loop) doesn’t affect or break down the whole theme. That’s a thing I did not mention — other “hacks” or workarounds might cause trouble. Thanks for pointing this out. 2nd hint: always keep backup!

Comments are closed.