hook – custom gravatar

Many themes use default Gravatar image for the WP User profile (what is Gravatar?). It is possible to change the profile icon with an uploaded image on the back-end installing a plugin, but it is also possible to do it on the front-end by a Toolset form.

The first step is to add an image custom user field to store the custom profile image.

The second step is to set up a create or edit user form with Toolset to upload the image on the frontend (it could be a complete create/edit WP user profile form).

The third step is to add this hook to alter the avatar image returned by the get_avatar() function:

//Custom Gravatar hook for Toolset

function wpv_custom_avatar( $avatar, $id_or_email, $size, $default, $alt ) {  

  // If provided an email and it doesn't exist as WP user, return avatar since there can't be a custom avatar
  $email = is_object( $id_or_email ) ? $id_or_email->comment_author_email : $id_or_email;
    if( is_email( $email ) && ! email_exists( $email ) )
    return $avatar;
  // Get the image from the user custom field
  $custom_avatar = do_shortcode("[types usermeta='custom-profile-image' size='thumbnail' url='true' user_id='".$id_or_email."'][/types]");

  // Return the custom avatar or the gravatar or de default avatar
  if ($custom_avatar) 
    $return = '<img src="'.$custom_avatar.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';
  elseif ($avatar) 
    $return = $avatar;
    $return = '<img src="'.$default.'" width="'.$size.'" height="'.$size.'" alt="'.$alt.'" />';

  return $return;

add_filter( 'get_avatar' , 'wpv_custom_avatar' , 10 , 5 );

get_avatar filter reference: https://developer.wordpress.org/reference/hooks/get_avatar/
get_avatar() reference: https://developer.wordpress.org/reference/functions/get_avatar/

Leave a Reply

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