Post Pic

Get most commented posts with thumbnails

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!

10 Responses

Jan 08 2010 12:37

Thanks for this codesnippet – great!

Greeting from germany, André

Jan 08 2010 15:57

nice… thanks for the code.. :D

Jan 09 2010 02:16

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?

Jan 09 2010 09:56

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..

Jan 09 2010 11:41

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?

Jan 09 2010 11:43

@lazaac: Custom field name is “Image” you can see it in get_post_meta() in the above code.

Jan 09 2010 17:15

Great piece of Wordpress hacking!

Jan 20 2010 20:48

Is there a way to turn this into an unordered list structure?

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required