How to Add a Custom Avatar to Your WordPress Profile

Wed, May 25th, 2022

If you work with WordPress, you likely know about Gravatar. However, if you want your users to be able to upload their own avatar, it’s not ideal for that use case. Here’s how I created one using Advanced Custom Fields and added the functionality in my site.

As a web developer, I often find myself working with WordPress. While it is a powerful platform, there are always areas where it could be improved. One lacking feature is the ability to upload and add your own avatar to your profile. Unfortunately, WordPress defaults to Gravatar for this feature. However, utilizing this simple piece of code in my functions.php file and the Advanced Custom Fields plugin, I am able to create a custom solution for users to add a custom image to their website profile. This allows for greater flexibility and customization for users, and it helps to make their website more personal. I’m excited to share this solution with other developers who may be looking for a similar resolution.


<?
//Add or Edit User Avatar
add_filter('get_avatar', 'tsm_acf_profile_avatar', 10, 5);
function tsm_acf_profile_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
    $user = '';
    // Get user by id or email
    if ( is_numeric( $id_or_email ) ) {
        $id   = (int) $id_or_email;
        $user = get_user_by( 'id' , $id );
    } elseif ( is_object( $id_or_email ) ) {
        if ( ! empty( $id_or_email->user_id ) ) {
            $id   = (int) $id_or_email->user_id;
            $user = get_user_by( 'id' , $id );
        }
    } else {
        $user = get_user_by( 'email', $id_or_email );
    }
    if ( ! $user ) {
        return $avatar;
    }
    // Get the user id
    $user_id = $user->ID;
    // Get the file id
    $image_id = get_user_meta($user_id, 'user_profile_picture', true); // CHANGE TO YOUR FIELD NAME
    // Bail if we don't have a local avatar
    if ( ! $image_id ) {
        return $avatar;
    }
    // Get the file size
    $image_url  = wp_get_attachment_image_src( $image_id, 'thumbnail' ); // Set image size by name
    // Get the file url
    $avatar_url = $image_url[0];
    // Get the img markup
    $avatar = '<img alt="' . $alt . '" src="' . $avatar_url . '" class="avatar avatar-' . $size . '" height="' . $size . '" width="' . $size . '"/>';
    // Return our new avatar
    return $avatar;
}
© 2023 Craig Allen. All rights reserved. Designing with purpose & vision.