Last active
October 21, 2020 20:19
-
-
Save kodie/829ddbfe70134642e9f29d5dda33c31f to your computer and use it in GitHub Desktop.
Allows for custom avatars to be pulled from usermeta in WordPress
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 | |
// Allows for custom avatars to be pulled from usermeta | |
add_filter('get_avatar_url', 'custom_user_avatar_url', 10, 3); | |
function custom_user_avatar_url($url, $id_or_email, $args) { | |
$image_url = false; | |
$user = false; | |
if (is_object($id_or_email) && isset($id_or_email->comment_ID)) { | |
$id_or_email = get_comment($id_or_email); | |
} | |
if (is_numeric($id_or_email)) { | |
$user = get_user_by('id', absint($id_or_email)); | |
} elseif (is_string($id_or_email)) { | |
if (strpos($id_or_email, '@md5.gravatar.com')) { | |
return $url; | |
} else { | |
$user = get_user_by('email', $id_or_email); | |
} | |
} elseif ($id_or_email instanceof WP_User) { | |
$user = $id_or_email; | |
} elseif ($id_or_email instanceof WP_Post) { | |
$user = get_user_by('id', (int) $id_or_email->post_author); | |
} elseif ($id_or_email instanceof WP_Comment) { | |
if (!empty( $id_or_email->user_id)) { | |
$user = get_user_by('id', (int) $id_or_email->user_id); | |
} | |
if ((!$user || is_wp_error($user)) && !empty($id_or_email->comment_author_email)) { | |
$user = get_user_by('email', $id_or_email->comment_author_email); | |
} | |
} | |
if (!$user) return $url; | |
// You can change this variable name to $image_url if you are storing image URLs instead of IDs | |
// Also, be sure to change the usermeta key to match whichever key you are storing the data | |
$image_id = get_user_meta($user->ID, 'profile_image_id', true); | |
if ( | |
!$image_url && $image_id && | |
$image = wp_get_attachment_image_src($image_id, array($args['width'], $args['height'])) | |
) $image_url = $image[0]; | |
if ($image_url) return $image_url; | |
return $url; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment