You can use the get_avatar_url
filter (see the arguments passed here in the source code) to change the avatar url and then simply use get_avatar()
with the user email in the theme as you’re used to.
add_filter('get_avatar_url', 'wpse_avatar_or_gravatar', 10, 3);
function wpse_avatar_or_gravatar($url, $id_or_email, $args) {
// was id passed via $id_or_email
if ($id_or_email == intval($id_or_email)) {
$userdata = get_userdata($id_or_email);
$email = $userdata->user_email;
}
// was email passed via $id_or_email
else {
$email = $id_or_email;
}
$path = sprintf('%s/images/users/%s.jpg',
WP_CONTENT_DIR,
md5($email . "customkey")
);
// image exists, return url
if (file_exists($path)) {
$url = sprintf('%s/images/users/%s.jpg',
WP_CONTENT_URL,
md5($email . "customkey")
);
}
else {
$url = "https://0.gravatar.com/avatar/" . md5($email . 'customkey') . "?s=64&d=identicon&f=y&r=g";
}
// image does not exist, return default avatar
return $url;
}