May
19
2009

How to List Your Most Popular Posts in WordPress

by   |  Posted in Tutorials  |  36 comments

I decided my sidebar was looking a little plain. It needed something more than just ads, so I placed a list of my popular posts there. I think it looks pretty cool and it was very simple to do. I just created a PHP function and added it to my functions.php files and then added some styles to get it to look the way I wanted.

First lets create the function. We’ll call it popularPosts. Be sure to add it between tags.

function popularPosts($num) {
    global $wpdb;
 
    $posts = $wpdb->get_results("SELECT comment_count, ID, post_title FROM $wpdb->posts ORDER BY comment_count DESC LIMIT 0 , $num");
 
    foreach ($posts as $post) {
        setup_postdata($post);
        $id = $post->ID;
        $title = $post->post_title;
        $count = $post->comment_count;
 
        if ($count != 0) {
            $popular .= '<li>';
            $popular .= '<a href="' . get_permalink($id) . '" title="' . $title . '">' . $title . '</a> ';
            $popular .= '</li>';
        }
    }
    return $popular;
}

Now to call the function, all we need to do is place this code wherever we want our list to appear. Let’s call for a list of 10 items by placing a ’10′ as our $num variable when we call our function.

<div class="popular">
    <h2>Most Popular Posts</h2>
    <ul>
        <?php echo popularPosts(10); ?>
    </ul>
</div>

All that is left is some styles to make it look good. Here are the styles I used for my sidebar list.

.popular {
	clear: both;
	float: left;
	margin: 10px 0;
	width: 283px;
	}
 
	.popular ul, .popular ul li {
		margin: 0;
		padding: 0;
		font-size: 12px;
		}
 
		.popular ul li {
			margin: 4px 0;
			padding-left: 20px;
			background: url(images/star.png) no-repeat 2px 2px;
			}
 
	.popular h2 {
		border: 0;
		border-bottom: 1px solid #aaa;
		font-size: 22px;
		font-weight: normal;
		font-family: Georgia,serif;
		margin: 0 0 15px;
		padding: 0 0 5px;
		}

For the star, I used this image star which I created in Illustartor.

Just right click above or drag the image to your desktop and add it to the appropriate directory to complete the look. You can also replace that image with whatever you want to appear there.

About the author:

A freelance web developer living in Montreal who spends most of his time writing for this site and building Premium themes for WordPress. You can find him on Twitter @bavotasan.

Site5 Affiliate Link
Share the love...

Tags: , , , , , , , , , ,

Short URL: http://bit.ly/bsEieb

Discussion 36 Comments