Created
November 13, 2023 12:24
-
-
Save wpgaurav/e3ee1c9b4c9be1166ea63e81bea8bcb9 to your computer and use it in GitHub Desktop.
Save Gravatars Locally and Display on WordPress Frontend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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