Skip to content

Instantly share code, notes, and snippets.

@wpgaurav
Created November 13, 2023 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpgaurav/e3ee1c9b4c9be1166ea63e81bea8bcb9 to your computer and use it in GitHub Desktop.
Save wpgaurav/e3ee1c9b4c9be1166ea63e81bea8bcb9 to your computer and use it in GitHub Desktop.
Save Gravatars Locally and Display on WordPress Frontend
<?php
// Code begins here. It can be pasted into WPCode or CodeSnippets plugin or functions.php file of your child theme
function my_custom_gravatar($avatar, $id_or_email, $size, $default, $alt) {
$email = '';
if (is_numeric($id_or_email)) {
$id = (int) $id_or_email;
$user = get_userdata($id);
if ($user) $email = $user->user_email;
} elseif (is_object($id_or_email)) {
if (!empty($id_or_email->user_id)) {
$id = (int) $id_or_email->user_id;
$user = get_userdata($id);
if ($user) $email = $user->user_email;
} elseif (!empty($id_or_email->comment_author_email)) {
$email = $id_or_email->comment_author_email;
}
} else {
$email = $id_or_email;
}
if ($email) {
$local_avatar_folder = WP_CONTENT_DIR . '/avatars/';
$local_avatar = $local_avatar_folder . md5(strtolower(trim($email))) . '.jpg';
$local_avatar_url = content_url('/avatars/') . md5(strtolower(trim($email))) . '.jpg';
if (!file_exists($local_avatar)) {
$gravatar_url = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s=' . $size;
$image_data = file_get_contents($gravatar_url);
if (!file_exists($local_avatar_folder)) {
mkdir($local_avatar_folder, 0777, true);
}
file_put_contents($local_avatar, $image_data);
}
$avatar = "<img alt='{$alt}' src='{$local_avatar_url}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
}
return $avatar;
}
add_filter('get_avatar', 'my_custom_gravatar', 10, 5);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment