Alex Denning over at WPSHOUT posted a nice tip for displaying popular posts without the need for a plugin. You can now order posts using the comment_count parameter in WordPress 2.9. He offered a couple different examples and the last one included adding an image along with the post. Well the latest version of WordPress not only lets you order posts by comment count but also includes the very handy the_post_thumbnail() function. We can use that instead of pulling the image from a custom field.
So how is it done?
First the feature needs to be turned on by including this line in your theme’s function.php:
add_theme_support('post-thumbnails');
Once that is added you can use the_post_thumbnail function in your theme. To accomplish what we’re going after we set up a new query to show the top five posts ordered by comment:
<?php $popular = new WP_Query('orderedby=comment_count&posts_per_page=5'); ?>
<?php while ($popular->have_posts()) : $popular->the_post(); ?>
Next we check to see if there is a thumbnail image and if there isn’t we display an alternate image instead:
<?php if ( has_post_thumbnail() ) the_post_thumbnail(array(60,60)); else echo '<img src="default.png" alt="Default Image" title="Default" />'; ?>
And finally we add the permalink for the post and close out the query:
<a href="<?php the_permalink(); ?>" rel="Bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a> <?php endwhile; ?>
You can also adapt this so it outputs an unordered list. Note: This is only going to work in versions 2.9 and up in WordPress. You can add backwards compatibility for the_post_thumbnail function but orderedby=comment_count only works in 2.9.
Here’s the entire query:
<?php $popular = new WP_Query('orderedby=comment_count&posts_per_page=5'); ?>
<?php while ($popular->have_posts()) : $popular->the_post(); ?>
<?php if ( has_post_thumbnail() )
the_post_thumbnail(array(60,60));
else echo '<img src="default.png" alt="Default Image" title="Default" />';
?>
<a href="<?php the_permalink(); ?>" rel="Bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
Check out the posts over at Kremalicious and WPEngineer for a lot more information on the_post_thumbnail function. And thanks to Alex Denning at WPSHOUT for the idea.

Delicious
Stumble It