The get_avatar_url WordPress PHP filter allows you to modify the avatar URL before it’s displayed on your website.
Usage
add_filter( 'get_avatar_url', 'your_custom_function_name', 10, 3 ); function your_custom_function_name( $url, $id_or_email, $args ) { // your custom code here return $url; }
Parameters
$url
(string) – The URL of the avatar.$id_or_email
(mixed) – The avatar to retrieve. Accepts a user ID, Gravatar MD5 hash, user email, WP_User object, WP_Post object, or WP_Comment object.$args
(array) – Arguments passed toget_avatar_data()
, after processing.
More information
See WordPress Developer Resources: get_avatar_url
Examples
Change avatar URL to a custom image
Replace the default avatar URL with a custom image for all users.
add_filter( 'get_avatar_url', 'custom_avatar_url', 10, 3 ); function custom_avatar_url( $url, $id_or_email, $args ) { $custom_url = 'https://yourwebsite.com/custom-avatar.jpg'; return $custom_url; }
Add a timestamp to the avatar URL
Prevent the browser from caching the avatar by adding a timestamp to the URL.
add_filter( 'get_avatar_url', 'timestamp_avatar_url', 10, 3 ); function timestamp_avatar_url( $url, $id_or_email, $args ) { $timestamp = time(); return $url . '?timestamp=' . $timestamp; }
Use a fallback image for missing avatars
Use a fallback image if the Gravatar service doesn’t have an avatar for the user.
add_filter( 'get_avatar_url', 'fallback_avatar_url', 10, 3 ); function fallback_avatar_url( $url, $id_or_email, $args ) { if ( ! $url ) { $url = 'https://yourwebsite.com/fallback-avatar.jpg'; } return $url; }
Change avatar URL based on user role
Display a different avatar image for users with the “editor” role.
add_filter( 'get_avatar_url', 'editor_avatar_url', 10, 3 ); function editor_avatar_url( $url, $id_or_email, $args ) { $user = false; if ( is_numeric( $id_or_email ) ) { $user = get_user_by( 'id', $id_or_email ); } elseif ( is_object( $id_or_email ) ) { $user = $id_or_email; } elseif ( is_string( $id_or_email ) ) { $user = get_user_by( 'email', $id_or_email ); } if ( $user && in_array( 'editor', $user->roles ) ) { $url = 'https://yourwebsite.com/editor-avatar.jpg'; } return $url; }
Replace Gravatar URL with a local image
Serve avatar images from your server instead of the Gravatar service.
add_filter( 'get_avatar_url', 'local_avatar_url', 10, 3 ); function local_avatar_url( $url, $id_or_email, $args ) { $parsed_url = parse_url( $url ); $local_url = get_site_url() . $parsed_url['path']; return $local_url; }