Display wordpress Recent Comments Without Widgets

November 18, 2008 · Print This Article

We know that you can easily display the recent comments with the help of a sidebar widget (If your WordPress blog supports widgets) but there is a simple solution that you can use to display recent comments without widgets, the following code will allow you to execute the recent comments in your blog anywhere in your template without widgets.

Two primary features:
It allows you to display recent comments without widgets.
It lets you control how many recent comments to display.

Firstly, open a new text file and place the following code in it.

function src_simple_recent_comments($src_count=7, $src_length=60, $pre_HTML='<li><h2>Recent Comments</h2>', $post_HTML='</li>') {

global $wpdb;

$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,
SUBSTRING(comment_content,1,$src_length) 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 $src_count";

$comments = $wpdb->get_results($sql);
$output = $pre_HTML;
$output .= "\n<ul>";
foreach ($comments as $comment) {
$output .= "\n\t<li><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID . "\" title=\"on " . $comment->post_title . "\"><strong>" . $comment->comment_author . "</strong></a>: " . strip_tags($comment->com_excerpt) . "...</li>";
$output .= "\n</ul>";
$output .= $post_HTML;
echo $output;

Save the above file as simple_recent_comments.php and put it in your theme folder (where your style.css is)

After you have saved this file in your theme folder, open your favorite template file where you wish to display recent comments. Say sidebar.php then put this very little snippet to display recent comments:

<?php include (TEMPLATEPATH . '/simple_recent_comments.php'); ?>
<?php if (function_exists('src_simple_recent_comments')) {
src_simple_recent_comments(10, 50, '', '');

The first line simply calls our simple_recent_comments.php file which we just created. You do not need to change anything. The second line lets you control how many comments to display, and the comment excerpt.

Using this block:

src_simple_recent_comments(10, 50, '', '');

For example; If I wanted to display 5 comments only, and use an excerpt of 30 words..I would change it to:

src_simple_recent_comments(5, 30, '', '');

Your choice for site templates and wordpress themes


Got something to say?

You must be logged in to post a comment.