Tutorial should include custom function for get_avatar_url, too

Support MB User Avatar Tutorial should include custom function for get_avatar_url, too

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #34519
    Stephen C.Stephen C.
    Participant

    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;
    }
    
    #34521
    Long NguyenLong Nguyen
    Moderator

    Hi,

    Thanks for your feedback.

    Some page builders like Elementor use the WordPress function get_avatar_url() to get the avatar URL instead of getting HTML code to show the avatar as the function get_avatar() return. I will update the article to cover this case.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.