WordPress: Popular Posts

Showing your blog’s most popular posts in the sidebar can attract visitors and give them an insight into your blog posts by looking at the ones that have been most widely discussed.

This tutorial will show you how you can use a simple piece of code to show your most popular posts, a bit like this:

popular posts

The Code

The best place to put this code is in your sidebar or footer, where you have other website statistics and such.

<h2>Popular Posts</h2>
	<?php $result = $wpdb->get_results("SELECT comment_count,ID,post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , 5");
		foreach ($result as $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 } } ?>


The parts in bold are the ones you can edit.

You do not need to place the posts in a bulleted list. They can be numbered if you like, or you can just use a <br /> after each post.

The comment number need not be in curly brackets; these can also be displayed how you like.

The number 5 is the number of posts that are displayed. Edit to your liking.

Stylesheet and CSS

You might need to change the margin and padding of your lists if you want to place the code in your sidebar. There might be too much padding (by default) so we can use an id to deal with this. We must change <ul> to <ul id="popular">. This assigns an id for that element.

<h2>Popular Posts</h2>
	<ul id="popular">

Next we must specify this element with CSS. The following goes in our stylesheet:

#popular {
	list-style-image:url('image URL');

Adjusting the padding on the left hand side will shift the list as far from the side as you wish.