Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.