How to: Display/ Pull Out Most Commented Posts On The Blog

This item was filled under [ Wordpress Tips/Hacks ]

Here’s some code to show your visitors the most commented posts on your blog.

Step 1. Backup your theme files. So if anything gets screwed up you can revert it.
Step 2. Load header.php of your theme. Look for </head> and before it add the following code:

<?php most_popular_posts($no_posts = 5, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
global $wpdb;
$request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
$request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
if(!$show_pass_post) $request .= " AND post_password =''";
if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
}
$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
$posts = $wpdb->get_results($request);
$output = '';
if ($posts) {
foreach ($posts as $post) {
$post_title = stripslashes($post->post_title);
$comment_count = $post->comment_count;
$permalink = get_permalink($post->ID);
$output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a> (' . $comment_count.')' . $after;
}
} else {
$output .= $before . "None found" . $after;
}
echo $output;
} ?>

Step 3. Save and upload it.

The value of “$no_posts=” can be changed to anything you’d like, depends upon the number of most commented posts you want to show.

Step 4. Figure Out where you want to display most commented posts and add the following piece of code:

<?php most_popular_posts(); ?>

Related Posts:

  • No Related Posts
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Comment