If you have comments enabled in WordPress, and if you are displaying Gravatar images for the comment authors, you will notice that WordPress, by default, adds a blank alt tag to the Gravatar images.
Recently, I audited my website using Screaming Frog. It gave me a lot of error warnings regarding the missing alt tags on gravatar images. For best SEO practice and accessibility, it is recommended that all the images on your website should have alt tags.
Since WordPress doesn’t specify the alt tag text for Gravatar images, we will use a simple function to insert the alt tag for the gravatar images.
To add alt tag to Gravatar images, please follow the steps below:
- Go to Appearance -> Theme File Editor
- Open Functions.php to edit from the right hand files list
- Copy and paste the following code at the end of functions.php
function gravatar_alt_text($gravatar1) {
if (have_comments()) {
$alt = get_comment_author();
}
else {
$alt = get_the_author_meta('display_name');
}
$gravatar1 = str_replace('alt=\'\'', 'alt=\'' . $alt . '\' title=\'' . $alt . '\'', $gravatar1);
return $gravatar1;
}
add_filter('get_avatar', 'gravatar_alt_text');
This code will add the name of the gravatar as an Alt tag.
1 comment
Soufiane
Thank you for the code, you really made my day and I was able to add ALT text to all my avatars.
Thanks!