There is get_avatar filter to replace avatar for user with ID 1. It works as intended.


But is it possible to match avatar for every user in comments section based on their login? I have a list of avatars in a certain folder and it basically needs to match nickname with image file.


Comment by Helldriver

Avatar src: wp-content/uploads/avatars/Helldriver.jpg

1 Answer 1


The get_avatar filter hook doesn't apply only to the user with the ID 1 – I'm assuming you have this idea because of the example from page about the get_avatar at the codex –, but in reality it targets the user according to the context it is used in, so every possible user, not solely the one. The hook is part of the get_avatar() function, which is a pluggable function and could be overridden, just to mention another possibility. Below I'm using the above mentioned example, basically just removing the conditional that checks for it being the user with the ID 1, to outline an exemplary, untested approach:

add_filter( 'get_avatar' , 'wpse322010_get_avatar' , 1 , 6 );
function wpse322010_get_avatar( $avatar, $id_or_email, $size, $default, $alt, $args ) {
    $user = false;

    if ( is_numeric( $id_or_email ) ) {
        $id = (int) $id_or_email;
        //see: https://developer.wordpress.org/reference/functions/get_user_by/
        $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 ) ) {
        //get upload dir data
        //see: https://developer.wordpress.org/reference/functions/wp_upload_dir/
        $upload_dir = wp_upload_dir();
        //get user data
        //see: https://developer.wordpress.org/reference/classes/wp_user/
        $user_id = $user->ID;
        //see: https://developer.wordpress.org/reference/functions/get_userdata/
        $user_info = get_userdata( $user_id );
        //using the username for this example
        $username = $user_info->user_login;
        //construct src
        $src = $upload_dir['baseurl'] . '/avatars/' . $username . '.jpg';
        $avatar = "<img alt='{$alt}' src='{$src}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";

    return $avatar;

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.