Skip to content

Instantly share code, notes, and snippets.

@wpgaurav
Created November 20, 2023 17:28
Show Gist options
  • Save wpgaurav/11faea09470b83e782216b7639cd6442 to your computer and use it in GitHub Desktop.
Save wpgaurav/11faea09470b83e782216b7639cd6442 to your computer and use it in GitHub Desktop.
Save Gravatars Locally and Display on WordPress Frontend
<?php
// Paste this in Code Snippets or Child Theme's functions.php file. Get Code Snippets at https://gauravtiwari.org/go/code-snippets
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) {
$hashed_email = md5(strtolower(trim($email)));
$local_avatar_folder = WP_CONTENT_DIR . '/avatars/';
$local_avatar_filename = $hashed_email . '_' . $size . '.jpg';
$local_avatar = $local_avatar_folder . $local_avatar_filename;
$local_avatar_url = content_url('/avatars/') . $local_avatar_filename;
if (!file_exists($local_avatar)) {
$gravatar_url = 'https://www.gravatar.com/avatar/' . $hashed_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