Use Local Avatar on your WordPress Site

If you’re running your own WordPress blog site and you want to use an avatar that is located on your own server instead of on gravator.com, you will need to make a small code change in /wp-includes/pluggable.php.

In the get_avatar function, and depending on which version of WordPress you’re using, you should find code that looks similar to this:

function get_avatar($id_or_email, $size='96', $default='', $alt=false) {
    . . .
    if ( !empty($email) ) {
        $out = "$host/avatar/";
        $out .= $email_hash;
        $out .= '?s='.$size;
        $out .= '&d=' . urlencode( $default );

        $rating = get_option('avatar_rating');
        if ( !empty( $rating ) )
            $out .= "&r={$rating}";

        $avatar = "<img alt='{$safe_alt}' <snip><snip> ";
    } else {
        $avatar = "<img alt='{$safe_alt}' <snip><snip> ";
    }
    . . .
}

Then add the following lines to it:

$upload_dir = wp_upload_dir();
if (file_exists($upload_dir['path']."/".$email_hash.".png")) {
    $out = $upload_dir['url']."/";
    $out .= $email_hash;
    $out .= ".png";
} else {
    . . .
}

Here’s the complete snippet illustrating where these lines should be added:

function get_avatar($id_or_email, $size='96', $default='', $alt=false) {
    . . .
    if ( !empty($email) ) {
        $upload_dir = wp_upload_dir();
        if (file_exists($upload_dir['path']."/".$email_hash.".png")) {
            $out = $upload_dir['url']."/";
            $out .= $email_hash;
            $out .= ".png";
        } else {
            $out = "$host/avatar/";
            $out .= $email_hash;
            $out .= '?s='.$size;
            $out .= '&amp;d=' . urlencode( $default );

            $rating = get_option('avatar_rating');
            if ( !empty( $rating ) )
                $out .= "&amp;r={$rating}";
        }

        $avatar = "<img alt='{$safe_alt}' <snip><snip> ";
    } else {
        $avatar = "<img alt='{$safe_alt}' <snip><snip> ";
    }
    . . .
}

Then upload your avatar as a 96×96 pixel png file via the “Add New” option under the “Media” section in the Admin screen. The name of the image file must be the hash based on your email, just like the one used to grab your avatar from the gravator.com site, followed by “.png”. For example bf844dff375a9559c5c4a0e4ea5585cd.png

In order to find what the hash value for your avatar file name should be, just open a screen that shows your avatar, whether it be the default one or your own, it doesn’t matter since it’s the same hash value that is included in the image URL to the the gravator.com site. Then either use the “View Source” function of your browser to find the <img src=". . ."> tag for the avatar, or right-click on the avatar itself and choose the “View Image Info” options from the context menu.

Avatar file name from HTML source code:
Avatar file name from Image Info:

Leave a Reply

Your email address will not be published. Required fields are marked *

*