
In order to help your visitors finding your best content, bloggers often display their most commented posts on their blog’s sidebar. In this recipe, I’ll show you how you can get most commented posts along with their related thumbnail.

In order to help your visitors finding your best content, bloggers often display their most commented posts on their blog’s sidebar. In this recipe, I’ll show you how you can get most commented posts along with their related thumbnail.
Nothing hard with this recipe : Simply paste this code anywhere in your theme files, where you'd like the most commented posts to be displayed. Don't forget to replace the custom field name by yours on line 5:
<?php $popular = new WP_Query('orderby=comment_count&posts_per_page=5'); ?>
<?php while ($popular->have_posts()) : $popular->the_post(); ?>
<?php $justanimage = get_post_meta($post->ID, 'Image', true);
if ($justanimage) { ?>
<img src="<?php echo get_post_meta($post->ID, "Image", true); ?>" alt="<?php the_title(); ?>" />
<?php } else { ?>
<img src="http://an-alternative-image.jpg" alt="" />
<?php } ?>
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php endwhile; ?>
Thanks to Alex Denning for this nice trick!
12 Responses
Thanks for this codesnippet – great!
Greeting from germany, André
nice… thanks for the code..
Nice code. If i’m reading it right does that mean it will show alternative-image.jpg if there is nothing in the custom field?
what’s the “custom field name” u mention about..? i can’t get it… don’t understand which one stand for field name… someone please help me..
thank you..
Very nice codesnippet. But I have a question:
Why are you calling get_post_meta second time? You can use $justanimage, it is more efficient. isn’t it?
@lazaac: Custom field name is “Image” you can see it in get_post_meta() in the above code.
Great piece of WordPress hacking!
Is there a way to turn this into an unordered list structure?
anybody know good plugin for related post with thumbnails, I try using some but not so good working…
That’s some good code man, thx!
Trackbacks: