Use the Person's Name as Avatar Alt Text
Fills the empty alt attribute of avatars with the display name of the user or commenter, so accessibility checkers stop reporting images without alt text.
Opens WPIDE on
Code
// Alt text for avatars that have none. %s is replaced with the person's display name.
$wpide_avatar_alt_pattern = '%s';
add_filter( 'get_avatar_data', function ( $args, $id_or_email ) use ( $wpide_avatar_alt_pattern ) {
if ( ! empty( $args['alt'] ) ) {
return $args;
}
$name = '';
if ( $id_or_email instanceof WP_Comment ) {
$name = $id_or_email->user_id ? get_the_author_meta( 'display_name', $id_or_email->user_id ) : $id_or_email->comment_author;
} elseif ( $id_or_email instanceof WP_User ) {
$name = $id_or_email->display_name;
} elseif ( $id_or_email instanceof WP_Post ) {
$name = get_the_author_meta( 'display_name', $id_or_email->post_author );
} elseif ( is_numeric( $id_or_email ) ) {
$name = get_the_author_meta( 'display_name', (int) $id_or_email );
} elseif ( is_string( $id_or_email ) && is_email( $id_or_email ) ) {
$user = get_user_by( 'email', $id_or_email );
$name = $user ? $user->display_name : '';
}
$name = trim( wp_strip_all_tags( (string) $name ) );
if ( '' !== $name ) {
$args['alt'] = sprintf( $wpide_avatar_alt_pattern, $name );
}
return $args;
}, 10, 2 );
Notes
Avatars that already have alt text keep it. Change the pattern to something like 'Photo of %s'. Snippets that replace the whole avatar image (such as Initials Avatars Instead of Gravatar) build their own tag, so this one does not change theirs.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.