Replace Gravatar images with coloured initials made on your own site, so visitors' email hashes are never sent to Gravatar.
add_filter( 'pre_get_avatar_data', function ( array $args, $id_or_email ): array {
$name = '';
if ( $id_or_email instanceof WP_Comment ) {
$name = $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', (int) $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 ) ) {
$name = strtok( $id_or_email, '@' );
}
$name = trim( (string) $name ) ?: '?';
$letter = mb_strtoupper( mb_substr( $name, 0, 1 ) );
$hue = hexdec( substr( md5( strtolower( $name ) ), 0, 2 ) ) * 360 / 255;
$size = (int) ( $args['size'] ?? 96 );
$svg = sprintf(
'<svg xmlns="http://www.w3.org/2000/svg" width="%1$d" height="%1$d" viewBox="0 0 100 100"><rect width="100" height="100" fill="hsl(%2$d,45%%,45%%)"/><text x="50" y="50" dy=".35em" text-anchor="middle" font-family="Arial,sans-serif" font-size="46" fill="#fff">%3$s</text></svg>',
$size,
(int) $hue,
esc_html( $letter )
);
$args['url'] = 'data:image/svg+xml;base64,' . base64_encode( $svg );
$args['found_avatar'] = true;
return $args;
}, 10, 2 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Every Gravatar image is loaded from Gravatar’s servers using a hash of the person’s email address. That shares visitor data with a third party and adds requests to every page with comments. This snippet makes avatars on your own site instead.
pre_get_avatar_data runs before WordPress builds an avatar URL. Setting $args['url'] means WordPress never contacts Gravatar.
The snippet finds a name for the comment, user or email, takes its first letter and picks a colour from the name, so the same person always gets the same colour. It draws a small SVG and returns it as a data URL, so there’s no extra file to load.
View a post with comments. Avatars should be coloured circles or squares with initials, and the browser’s network panel should show no requests to gravatar.com.