Create a Custom Function to Display a User's Gravatar in WordPress

Emily S Dec 19, 2024 User Experience
How can I show my users' profile pictures next to their comments on my website?
What is the best way to create a custom function in WordPress to display a user's Gravatar image next to their comments, ensuring it adheres to best practices for performance and security?
Andy answered Dec 19, 2024

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:

  1. WP User Avatar - Allows users to upload custom avatars
  2. Simple Local Avatars - Enables local avatar uploads with Gravatar fallback
  3. 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.