Here is a simple and effective way to create a list of your most popular (most commented) posts without using a plugin. First, add the following to your theme's functions.php file ...
function most_popular_posts($no_posts = 10, $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;
}
What we have just done is create a new function called most_popular_posts. Now all we have to do is use our new function. Open sidebar.php and add <?php most_popular_posts(); ?> wherever you want the list to appear. Using the default Kubrick theme as an example, you would have this ...
<li><h2>Popular</h2>
<ul><?php most_popular_posts(); ?></ul>
</li>
To control the number of posts in the list look for the line $no_posts = 10 and change the value to whatever you want. Simple, yes?
Thanks for this tip - I need that for a theme I am developing,
Banago’s last blog post..Accessible CSS
You're most welcome Banago.
By the way, I've learned quite a bit from you as your blog is one of my regular reads.
very useful post tahnks
A bit lazy will install ur code today
hi sorry but I think theres some prob in ur query It does not display all-time popular posts I dont know on what basis it was piking the results So sorry have to remove ur code
Hi Atul. How are you implementing it? I just tested it on a local install and it worked fine.
hi, i want to style the popular posts list (successfully implemented, thanks) with this code:
<a href=""><img src="ID, "Thumbnail", true);?>" /> <a href="">
can you help me understand how I can include the custom field assigned thumbnail to each listed post?
Hi Sven. Here is a link to a tutorial which describes a better method than the one I provided.
Thank you! Just got rid of one more plugin and implemented the code easily
You're most welcome Zhu.