Display most popular content in wordpress sidebar

March 26, 2009 · Print This Article

Highlighting the most popular posts on your site is a great way to send new visitors to your very best content and win them over.

What about giving them a quick access to your most commented posts? There are a few different ways you can do this, and quite a few plugins out there to help.

What we’re going to do is quite simple, we will set up a query to get an ordered list of your most commented posts from your database, and then display those any way we like.

Setting this up as a sidebar widget is very easy. Just copy and paste the code below into your sidebar.php file.

To change the number of posts shown, just change the “8” at the end of line 3 to whatever number you would like.

<h2>Popular Posts</h2>
<ul>
<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 8");
foreach ($result as $post) {
setup_postdata($post);
$postid = $post->ID;
$title = $post->post_title;
$commentcount = $post->comment_count;
if ($commentcount != 0) { ?>
<li><a href="<?php echo get_permalink($postid); ?>" title="<?php echo $title ?>">
<?php echo $title ?></a> {<?php echo $commentcount ?>}</li>
<?php } } ?>
</ul>

Instead of simply having the list in your sidebar, you could create a longer list to show a lot more of your best posts, and put this list in its own page.


Your choice for site templates and wordpress themes

Comments

Got something to say?

You must be logged in to post a comment.