Custom user avatar in the WordPress users listing

As an alternative to my other answer, you can also use the get_avatar filter. Props to Sumit to alerting me to this one.

The benefit of using the get_avatar filter is your custom avatar should be applied anywhere WordPress uses it, rather than just in this users list like my other answer deals with. If you use plugins that display user avatars, this solution should also work for them, providing they play nicely and use the WordPress filters they should be using 🙂

The official docs for the get_avatar filter are here.

In your theme’s functions.php, you’ll want set up your function like this:

add_filter("get_avatar", "wpse_228870_custom_user_avatar", 1, 5);

function wpse_228870_custom_user_avatar($avatar, $id_or_email, $size, $alt, $args){

  // determine which user we're asking about - this is the hard part!
  // ........

  // get your custom field here, using the user's object to get the correct one
  // ........

  // enter your custom image output here
  $avatar="<img alt="" . $alt . '" src="https://wordpress.stackexchange.com/questions/228870/image.png" width="' . $size . '" height="' . $size . '" />';

  return $avatar;

}

Now there’s a lot missing from that because, perhaps frustratingly, WordPress doesn’t send a nice clean user object or user ID through to this filter – according to the docs it can give us:

a user_id, gravatar md5 hash, user email, WP_User object, WP_Post object, or WP_Comment object

Most of these we can deal with – if we got a Gravatar hash that’d be a bit difficult – but the rest we can use the built in WordPress functions to get the correct user object.

There’s an example that gets started on this in the old WordPress docs. However for this filter to work properly everywhere it’s used, you’ll need to write a little extra to make sure you can detect and deal with a post or comment object coming through as well (perhaps using the PHP is_a function) and then getting the associated post or comment author.

Leave a Comment