Initials Avatars Instead of Gravatar
Replaces Gravatar images with colored circles showing each person's initials, generated locally, so no visitor data is sent to Gravatar.
Opens WPIDE on
Code
add_filter( 'pre_get_avatar', function ( $html, $id_or_email, $args ) {
if ( null !== $html || ( empty( $args['force_display'] ) && ! get_option( 'show_avatars' ) ) ) {
return $html;
}
$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 ) ) {
$user = get_user_by( 'email', $id_or_email );
$name = $user ? $user->display_name : strtok( $id_or_email, '@' );
}
$name = trim( (string) $name );
$parts = preg_split( '/[\s._-]+/u', $name, -1, PREG_SPLIT_NO_EMPTY );
$initials = '';
foreach ( array_slice( (array) $parts, 0, 2 ) as $part ) {
$initials .= function_exists( 'mb_substr' ) ? mb_strtoupper( mb_substr( $part, 0, 1 ) ) : strtoupper( substr( $part, 0, 1 ) );
}
$initials = '' !== $initials ? $initials : '?';
$hue = abs( crc32( $name ) ) % 360;
$width = (int) ( ! empty( $args['width'] ) ? $args['width'] : $args['size'] );
$height = (int) ( ! empty( $args['height'] ) ? $args['height'] : $args['size'] );
$svg = sprintf(
'<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="hsl(%d,45%%,45%%)"/><text x="50" y="50" dy=".35em" text-anchor="middle" font-family="Arial,Helvetica,sans-serif" font-size="42" fill="#fff">%s</text></svg>',
$hue,
htmlspecialchars( $initials, ENT_QUOTES | ENT_XML1, 'UTF-8' )
);
$class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
if ( ! empty( $args['class'] ) ) {
$class = array_merge( $class, (array) $args['class'] );
}
return sprintf(
'<img alt="%1$s" src="%2$s" class="%3$s" height="%4$d" width="%5$d" %6$s>',
esc_attr( $args['alt'] ),
esc_attr( 'data:image/svg+xml;base64,' . base64_encode( $svg ) ),
esc_attr( implode( ' ', $class ) ),
$height,
$width,
isset( $args['extra_attr'] ) ? $args['extra_attr'] : ''
);
}, 10, 3 );
Notes
Avatar URLs in the REST API still point to Gravatar; only images shown on your pages change.
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.