How to set custom avatar for users?

We can use the get_avatar_url filter to modify the avatar’s url.

If all the relevant get_avatar() calls, have user id as an input argument, then it’s easy to get the corresponding user’s meta value, with get_user_meta(), within the filter’s callback.

Otherwise we need to handle all possible input cases, for get_avatar( $some_input ), as it supports:

  • user id,
  • user email,
  • gravatar md5 hash,
  • WP_User object,
  • WP_Post object
  • WP_Comment object.

We can look into the get_avatar_data() function, to get an idea how to write such checks.

An alternative, to determine the user id from the get_avatar() input, we might try to fetch the md5 hash from the generated gravatar url and use it to determine the user id from it. Maybe store the md5 email hash for each user.
The found_avatar argument might also help, as it’s true if the avatar was found for the given user.

Hope it helps!