Using Gravatar in WordPress Comments
Custom Code Solution
The following code fetches and displays Gravatar images next to user comments. Place this code in your theme's functions.php
file:
Get user's Gravatar based on their email address:
function get_custom_gravatar($email, $size = 60) {
$hash = md5(strtolower(trim($email)));
$rating = 'g'; // Rating: g, pg, r, x
$default = 'mm'; // Default image: mm, identicon, monsterid, wavatar, retro
return sprintf('https://www.gravatar.com/avatar/%s?s=%d&d=%s&r=%s',
$hash,
$size,
$default,
$rating
);
}
Hook into WordPress comment display to add Gravatar:
function custom_comment_gravatar($comment, $args, $depth) {
$gravatar_url = get_custom_gravatar($comment->comment_author_email);
?>
<li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>">
<div class="comment-gravatar">
<img src="<?php echo esc_url($gravatar_url); ?>"
alt="<?php echo esc_attr($comment->comment_author); ?>'s avatar"
width="60"
height="60">
</div>
<div class="comment-content">
<cite class="comment-author"><?php comment_author(); ?></cite>
<?php comment_text(); ?>
</div>
</li>
<?php
}
Add this CSS to your theme's stylesheet:
add_action('wp_head', function() {
?>
<style>
.comment-gravatar {
float: left;
margin-right: 15px;
}
.comment-content {
margin-left: 75px;
}
</style>
<?php
});
Use the custom comment callback in your template:
wp_list_comments(array(
'callback' => 'custom_comment_gravatar'
));
Plugin Solutions
If you prefer using a plugin, here are reliable options:
-
WP User Avatar - Allows users to upload custom avatars
-
Simple Local Avatars - Enables local avatar uploads with Gravatar fallback
-
Basic User Avatars - Lightweight solution for custom avatars
Additional Notes
- The code uses a default size of 60 pixels, which you can adjust in the
get_custom_gravatar()
function
- The default Gravatar rating is 'g' (suitable for all audiences)
- The fallback avatar is set to 'mm' (mystery man)
- The code includes basic CSS styling which you can customize
- All output is properly escaped for security
Remember to test the implementation thoroughly after adding the code to your theme.