0

I have built my own frontend user avatar upload script. Now the avatars show fine in the user section in admin and in the top panel. However I can't seem to get them showing in the comments and author sections of the site.

I use the following get_avatar code

  add_filter ('get_avatar', function($avatar_html, $id_or_email, $size, $default, $alt) {
    $avatar = get_user_meta($id_or_email,'avatar',true);
    if( $avatar ) {
        return '<img src="'.$avatar.'" width="96" height="96" alt="Avatar" class="img-fluid rounded-circle" id="wad_profile_avatar" />';
    } else {
        return $avatar_html;
}
}, 10, 5);

Any ideas how I can get it to show in comments also?

1 Answer 1

0

I found a solution and now my frontend avatar script is fully functioning.

Happy days :)

I ended up scrapping the above code and using this.

add_filter( 'pre_get_avatar_data', 'wad_avatar_meta', 10, 2 );

function wad_avatar_meta( $args, $id_or_email ){
    $user_avatar_meta_key = 'avatar';

    if( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ){
        $id_or_email = get_comment( $id_or_email );
    }

    if( $id_or_email instanceof WP_Post ){
        $user_id = $id_or_email->post_author;
    }

    if( $id_or_email instanceof WP_Comment ){
        if( ! empty( $id_or_email->user_id ) ){
            $user_id = $id_or_email->user_id;
        } elseif( ! empty( $id_or_email->comment_author_email ) ){
            // If user_id not available, set as email address to handle below
            $id_or_email = $id_or_email->comment_author_email;
        }
    }

    if( is_numeric( $id_or_email ) ){
        $user_id = $id_or_email;
    } elseif( is_string( $id_or_email ) && strpos( $id_or_email, '@' ) ){
        $id_or_email = get_user_by( 'email', $id_or_email );
    }

    if( $id_or_email instanceof WP_User ){
        $user_id = $id_or_email->ID;
    }

    if( ! empty( $user_id ) && is_numeric( $user_id ) ){

        $meta_val = maybe_unserialize( get_user_meta( $user_id, $user_avatar_meta_key, TRUE ) );

        if( ! empty( $meta_val ) ){

            if( is_array( $meta_val ) && ! empty( $meta_val[0] ) ){
                $meta_val = $meta_val[0];
            }

            if( filter_var( $meta_val, FILTER_VALIDATE_URL ) ){
                $args['url'] = $meta_val;
            }

        }
    }

    return $args;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.