I have a feature that allows users to upload their own images as avatars. The uploaded images are stored correctly in the meta_key named image. So it works.
The point is that uploaded images don't show up in the comments section, admin panel, or anywhere on the site. This is because wordpress does not use the image meta_key to display images, but it does with the get_avatar filter.
What I am trying to do is set the meta_key image in the get_avatar filter, this way the user avatars should be visible in the comments section, reviews and everywhere on the site.
I'm trying to run the code below and it only works for the admin section, so in the backend I can actually see the avatars uploaded by each user. But gravatar's default images still appear everywhere in the front-end of the site.
What am I doing wrong ?
// Replace default Gravatar Image used in WordPress
add_filter( 'get_avatar', 'filter_get_avatar', 10, 5 );
function filter_get_avatar( $avatar, $current_user, $size, $default, $alt ) {
// If is email, try and find user ID
if ( ! is_numeric( $current_user ) && is_email( $current_user->comment_author_email ) ) {
$user = get_user_by( 'email', $current_user );
if ( $user ) {
$current_user = get_current_user_id();
}
}
// If not user ID, return
if( ! is_numeric( $current_user ) ) {
return $avatar;
}
// Get attachment id
$attachment_id = get_user_meta( $current_user, 'image', true );
// NOT empty
if ( ! empty ( $attachment_id ) ) {
// Return saved image
return wp_get_attachment_image( $attachment_id, [ $size, $size ], false, ['alt' => $alt] );
}
return $avatar;
}
Update:
In this way the images are displayed in the comments section, admin and I believe also elsewhere on the site. But the problem is that all users get the same image. What am I doing wrong ?
function wdoc_filter_get_avatar_url( $url, $id_or_email, $args ) {
$current_user_id = get_current_user_id();
$file_id = get_user_meta( $current_user_id, 'image' , true );
return wp_get_attachment_image_url($file_id);
}
add_filter( 'get_avatar_url', 'wdoc_filter_get_avatar_url', 10, 3 );

所有评论(0)