Theme & Front End PHP Beginner

Use Your Own Default Avatar

Replace the generic mystery person Gravatar shown for users without a profile image with your own custom default avatar hosted on your site.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 15 lines
// The image must be publicly reachable: Gravatar fetches it from your site.
function nahnu_default_avatar_url(): string {
	return get_stylesheet_directory_uri() . '/images/default-avatar.png';
}

// Add it to Settings > Discussion > Default Avatar.
add_filter( 'avatar_defaults', function ( array $defaults ): array {
	$defaults[ nahnu_default_avatar_url() ] = 'Site default avatar';
	return $defaults;
} );

// Use it straight away, without changing the setting by hand.
add_filter( 'pre_option_avatar_default', function (): string {
	return nahnu_default_avatar_url();
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

People without a Gravatar account get WordPress’s grey “mystery person” silhouette next to their comments and in author boxes. This snippet replaces it with your own image, such as a branded icon.

How it works

WordPress asks Gravatar for each avatar and passes a “default” image address for people who don’t have one. The avatar_defaults filter adds your image to the choices under Settings → Discussion, and the pre_option_avatar_default filter selects it, so you don’t have to change the setting by hand.

The previous version tried to swap the final avatar URL by looking for d=mp inside it. That only matched when the setting was on “Mystery Person”, so on many sites nothing changed. Working through the setting itself is reliable and is how WordPress expects it to be done.

Things to watch

  • Gravatar downloads your image from your site, so it must be publicly reachable. It won’t work on a local or password-protected site.
  • Use a square image, at least 256 by 256 pixels. Gravatar scales it to each size WordPress asks for.
  • People who do have a Gravatar still see their own picture.

How to test it

Upload default-avatar.png to an images folder in your active (child) theme, then view a post with a comment from someone without a Gravatar. Settings → Discussion should also show “Site default avatar” selected.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only