Add Most Popular Posts List to WordPress

Today I had a project that required the addition of a list of the top ten most popular posts to the sidebar of a WordPress blog. Here is the code I eventually got to work after trying several plugins that did not work because of the custom theme I was using. So if you have a similar problem, use this simple code snippet to show the top ten posts according to the number of comments made on each.

Add this code wherever in your theme template you want the most popular posts to display. I wrote this code for the sidebar, so I put mine in sidebar.php:

<!–posts by popularity:–>
<br /><br />
<div>
    <h3>Most Popular Posts</h3>
</div>

<div>
<ul>
<?php
$popular_posts = $wpdb->get_results(“SELECT id,post_title FROM {$wpdb->prefix}posts WHERE post_status=’publish’ AND post_type=’post’ ORDER BY comment_count DESC LIMIT 0,10”);
foreach($popular_posts as $post) {
    print “<li><a href='”. get_permalink($post->id) .”‘>”.$post->post_title.”</a></li>n”;
}
?>
</ul>
</div>

Then you can add your own styles in style.css or use the ones I did below:

.related_head{
width:320px;
border:2px solid #f9a86f;
background:#f9a86f;
border-radius:15px 15px 0px 0px; /*topleft, topright, bottomright, bottomleft*/
}

.related_head h3{
text-align:center;
text-decoration: underline;
font-size:135%;
color:#dbe475;
}

.related_content{
width:320px;
border:2px solid #f9a86f;
border-radius:0px 0px 15px 15px;
}

.related_content a{
font-size:125%;
}

Leave a Reply

Your email address will not be published. Required fields are marked *