Though this isn’t quite the same as displaying your most popular posts in your sidebar, here is some code you can use to display the posts that have received the most comments.  You’ll want to place it in your sidebar where you want the code to be displayed.

Most Commented Posts Code

Go into your theme files and go to header.php file.   Somewhere within the </head> you’ll want to place the following code:

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

If you’d prefer to display more than 5 posts, you can change the $no_posts = 5 code to whatever number you want to display.

Okay, now, you need to figure out where you want to display these most commented posts (usually the sidebar) and place the following code:

&amp;lt;?php most_popular_posts(); ?&amp;gt;

And as is usually the case, if you want something easier, you can always go with a plugin such as the Popularity Contest plugin.

To see other code that we’ve featured, check out our WordPress Code page.

Republished by Blog Post Promoter