How to add a CSS class to the Gravatar image in WordPress

To add a CSS class to the Gravatar image in WordPress, you can use the get_avatar filter. Here’s how you can do it:

  1. In your WordPress admin dashboard, go to “Appearance” > “Theme Editor.”
  2. In the right sidebar, locate and click on the “functions.php” file.
  3. Add the following code snippet at the end of the file:
function my_theme_add_gravatar_class($avatar_html) {
    // Define the CSS class you want to add
    $css_class = 'my-custom-gravatar-class';

    // Add the class to the Gravatar image
    $avatar_html = str_replace("class='avatar", "class='avatar {$css_class}", $avatar_html);

    return $avatar_html;
}
add_filter('get_avatar', 'my_theme_add_gravatar_class');

Replace ‘my-custom-gravatar-class’ with the desired CSS class you want to add to the Gravatar image.

  1. Click “Update File” to save the changes.

Now, the specified CSS class will be added to all Gravatar images on your WordPress site.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *