How to Change Avatar in WordPress Using Code

Last Updated on November 11, 2023 by Mike Kipruto

Today I want to share a quick and easy tutorial on changing Avatar images in WordPress using custom code.

To achieve this, we are going to make use of the following code that adds a filter to modify the avatar data using the get_avatar_data hook filter.

PHP
<?php
add_filter('get_avatar_data', 'change_the_avatar', 100);

function change_the_avatar($args) {
    $img = get_field("image", "user_" . get_current_user_id());
    $args['url'] = $img;
    return $args;
}

It defines a function change_the_avatar that accepts the avatar data arguments and modifies the URL by replacing it with the value from a custom field named “image” which is an Image field added using the Advanced Custom Fields (ACF) plugin to the user.

The custom field value is retrieved using the get_field function, specifying the field name and the user ID of the current user as outlined here as shown:

The image field has its return format settings set to Image URL, for more details on to go about please take a look at this guide.

Finally, the modified avatar data arguments are returned.