Article
Using commenters initials as Avatar

Extending the walker comment class in WordPress. Query Gravatar and creat the initials from the username string.

Comment List

First of all we have to set up the comment list in comments.php. Except for the marked lines the values are default. See: wordpress/wp-list-comments

wp_list_comments( array(
    'walker'            => new comment_walker(),
    'max_depth'         => '',
    'style'             => 'ul',
    'callback'          => null,
    'end-callback'      => null,
    'type'              => 'all',
    'page'              => '',
    'per_page'          => '',
    'avatar_size'       => 32,
    'reverse_top_level' => null,
    'reverse_children'  => '',
    'format'            => 'html5',
    'short_ping'        => false,
    'echo'              => true,
);

Line 2: Use the new comment walker class which is described in the next section.

Line 13: Set the format to html5 because we extend the corresponding class.

Walker Comment Class

The following function is used by WordPress to set up the comment list markup. See: wordpress/html5-comment
For displaying the initials we have to extend line 9 and wrap the function with class comment_walker extends Walker_Comment {...}. You can manipulate the class further to get the html markup you need.

class comment_walker extends Walker_Comment {
    protected function html5_comment( $comment, $depth, $args ) {
        $tag = ( 'div' === $args['style'] ) ? 'div' : 'li';
?>
        <<?php echo $tag; ?> id="comment-<?php comment_ID(); ?>" <?php comment_class( $this->has_children ? 'parent' : '', $comment ); ?>>
            <article id="div-comment-<?php comment_ID(); ?>" class="comment-body">
                <footer class="comment-meta">
                    <div class="comment-author vcard">
                        <?php if ( 0 != $args['avatar_size'] ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
                        <?php
                            /* translators: %s: comment author link */
                            printf( __( '%s <span class="says">says:</span>' ),
                                sprintf( '<b class="fn">%s</b>', get_comment_author_link( $comment ) )
                            );
                        ?>
                    </div><!-- .comment-author -->
 
                    <div class="comment-metadata">
                        <a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
                            <time datetime="<?php comment_time( 'c' ); ?>">
                                <?php
                                    /* translators: 1: comment date, 2: comment time */
                                    printf( __( '%1$s at %2$s' ), get_comment_date( '', $comment ), get_comment_time() );
                                ?>
                            </time>
                        </a>
                        <?php edit_comment_link( __( 'Edit' ), '<span class="edit-link">', '</span>' ); ?>
                    </div><!-- .comment-metadata -->
 
                    <?php if ( '0' == $comment->comment_approved ) : ?>
                    <p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.' ); ?></p>
                    <?php endif; ?>
                </footer><!-- .comment-meta -->
 
                <div class="comment-content">
                    <?php comment_text(); ?>
                </div><!-- .comment-content -->
 
                <?php
                comment_reply_link( array_merge( $args, array(
                    'add_below' => 'div-comment',
                    'depth'     => $depth,
                    'max_depth' => $args['max_depth'],
                    'before'    => '<div class="reply">',
                    'after'     => '</div>'
                ) ) );
                ?>
            </article><!-- .comment-body -->
<?php
    }
}

Line 1: Extend the core walker class.

Line 9: Exchange the code with the following.

Line 51: Close the function.

Validation and Initials

Just replace the marked line 9 from the previous section with the following code.
We check for the existence of a Gravatar and if nothing is found we will receive a 404 error instead of a default image. I used the get_avatar_url() function to gain the gravatar validation. You can also use the method described by wordpress/Checking-Gravatar-Existence or this more full featured method from github/validate-gravatar. After that we generate the initials and display the appropriate markup.

<?php
if ( 0 != $args['avatar_size'] ) {
    $avatarUrl = get_avatar_url( $comment, array( 'default' => '404' ) );
    $response = wp_remote_head( $avatarUrl );
    $headCode = $response['response']['code'];

    if ( $headCode == '200' ) {
        echo get_avatar( $comment, $args['avatar_size'] );
    } else {
        $commentAuthor = $comment->comment_author;
        $spacePosition = strpos( $commentAuthor, ' ' );
        printf(
            '<div class="avatar initials" style="height:%1$spx; width:%1$spx;"><span>%2$s%3$s</span></div>',
            $args['avatar_size'],
            $commentAuthor[0],
            $spacePosition !== false ? $commentAuthor[$spacePosition + 1] : ''
        );
    }
}
?>

Line 10: If the avatar size isn't zero go on. The size can be set in wp_list_comments().

Line 11: Get the avatar url and set the default to 404, so if no avatar has bin found the url contains an error 404. See: wordpress/get-avatar-url

Line 12: Retrieve the raw response from the HTTP request. An image would have the response code 200. See: wordpress/wp-remote-head

Line 14, 15: If the response code is 200 display the avatar image.

Line 17: If the response code isn't 200 or a WP_Error occurred, display commenters initials.

Line 18: Get the comment author name.

Line 19: Get the position of the first space if there is one.

Line 21: Width and height of the initials container.

Line 23: Set the first character.

Line 24: Set the first character after the first space.

Conclusion

The only bummer is if a commenter uses different names for the posts we will generate different initials. But for me it is still better than a random image.

Leave the first comment

  • required
  • required, will not be published