How to Show Recent Comments with Avatar in WordPress Sidebar Without using a Plugin

Advertisement

It’s been a while now since I updated my website theme, so now I decided to create a brand new 2017 theme, horraayyy, and the lists of the features are, display popular posts, recent posts and recent comments all with gravatar in it, and it does not require any plugin that could drag your site away from Google Index for page load issue, how cool is that? now, are you looking for one or wanted to try it in your website or projects too? Well, you’re in the right place.

WordPress does provide us a very handy PHP class WP_Comment_Query to retrieve all website comments at once and it also comes with lots of returned property or data.

So let’s get started

The Display

This just all we need to display lists of Recent Comments in the front-end area.


<ul class="list-unstyled rs-recent-comments">
	<?php
		$comment_args = array(
			'status' => 'approve',
			'number' => $instance['comment_count'],
		);

		// The Query
		$comments_query = new WP_Comment_Query;
		$comments 		= $comments_query->query( $comment_args );

		// Comment Loop
		if ( $comments ) {
			foreach ( $comments as $comment ) {

				?>
					<li class="ml-0">
						
						<div class="list-left">
							<?php echo get_avatar( $comment->comment_author_email, 60 ); ?>
						</div>
						<div class="list-right">
							<p>
								<a href="<?php echo esc_url( $comment->comment_author_url ); ?>">
									<?php echo $comment->comment_author; ?>
								</a>

								<span>on</span>
								
								<a href="<?php echo esc_url( get_permalink( $comment->comment_post_ID ) ); ?>">
									<?php echo $comment->post_name; ?>
								</a>
							</p>
						</div>
					
					</li>
				<?php
			}
		} else {

			__e( '<p>No comments added yet.</p>', 'rs-theme' );

		}
	?>
</ul>

CSS

It’s time to make it more elegant and appealing to look, just like what I have here added on my blog.


.rs-recent-comments .list-left {
    width: 60px;
}
.rs-recent-comments .list-left,
.rs-recent-comments .list-right {
    display: table-cell;
}
.rs-recent-comments .list-right {
    padding-left: 1em;
    vertical-align: middle;
}

I’d suggest for better performance and reusable code, make the above code into a Theme Widget or Plugin.

That’s it and we’re pretty much done happy coding ^_^

References and Credits

WP_Comment_Query

Advertisement