I followed the https://metabox.io/create-custom-avatar/ tutorial, but found that the avatar only displayed in some places on my site even though the get_avatar function was used to display it. However, creating a custom get_avatar_url function as well, seemed to fix the problem and now the avatar displays correctly wherever it should.
This is the code I ended up using:
add_filter( 'get_avatar' , 'my_custom_avatar' , 1 , 5 );
function my_custom_avatar( $avatar, $id_or_email, $size, $default, $alt ) {
$url = my_custom_avatar_url( $avatar, $id_or_email, $size );
if (!empty($url)){
$avatar = "<img src='" . $url . "' class='avatar avatar-" . $size . " photo' alt='" . $alt . "' height='" . $size . "' width='" . $size . "' />";
}
return $avatar;
}
add_filter( 'get_avatar_url' , 'my_custom_avatar_url' , 1 , 3 );
function my_custom_avatar_url( $avatar, $id_or_email, $size ) {
$user = false;
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 && is_object( $user ) ) {
$value = rwmb_meta( 'user_avatar', array( 'object_type' => 'user' ), $user->data->ID );
if ( $value ) {
$avatar = $value['url'];
}
}
return $avatar;
}