Display Recent Comments in WordPress Sidebar (with Post Title)
You can display a list of recent comments in your WordPress sidebar or any other template location without a plugin. The format will be 'Username: commented on "Post Title"'.
Core Code & Implementation
Add the following code to your theme's sidebar.php file (or any template file where you want the list to appear). It queries approved comments and displays them in reverse chronological order.
<?php
global $wpdb;
$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID,
comment_post_ID, comment_author, comment_date_gmt, comment_approved,
comment_type, comment_author_url,
SUBSTRING(comment_content, 1, 30) AS com_excerpt
FROM $wpdb->comments
LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID)
WHERE comment_approved = '1' AND comment_type = '' AND post_password = ''
ORDER BY comment_date_gmt DESC
LIMIT 9";
$comments = $wpdb->get_results($sql);
if ($comments) {
echo '<ul>';
foreach ($comments as $comment) {
$author = strip_tags($comment->comment_author);
$title = strip_tags($comment->post_title);
$permalink = get_permalink($comment->comment_post_ID);
$comment_link = $permalink . '#comment-' . $comment->comment_ID;
echo "<li><strong>{$author}</strong>: <a href='{$comment_link}' title='View this comment'>commented on "{$title}"</a></li>";
}
echo '</ul>';
} else {
echo '<p>No comments yet.</p>';
}
?>
Code Explanation & Customization
- Number of Comments: Change the number in
LIMIT 9to adjust how many comments are shown. - Query Conditions:
comment_approved = '1'ensures only approved comments are shown;post_password = ''excludes password-protected posts. - Output Format: The code outputs a valid HTML list with corrected quote usage and link structure.
- Security:
strip_tags()filters the username and post title to prevent XSS attacks.
Advanced Optimization Tips
- Create a Widget: For more flexible management, wrap this code into a simple WordPress Widget.
- Add Caching: Frequent database queries can impact performance. Consider caching the results using
wp_cache_set()andwp_cache_get(). - Style Customization: The output uses
<ul>and<li>tags, which can be styled via your theme's CSS.
Note: Directly editing theme files will cause changes to be lost during theme updates. It is recommended to manage custom code using a child theme or a code snippets plugin.