Get thumbnails from specific wordpress posts

January 16, 2009 · Print This Article

Nowadays, many WordPress users are using a custom field to illustrate their posts with a thumbnails, then how to get the thumbnails related to a specific kind of posts, most commented?

To get a list of thumbnails from the most commented post, we have to use a SQL request and some PHP.

Paste the following code anywhere on your theme, where you’d like the thumbnails to be displayed. Each thumbnail contains a link to read the associated post.


//The name of custom field you'd like to get, don't forget to change it
$custom_field_name = "featuredimg";

//Cool sql request
$sql = "SELECT p.comment_count, p.ID, m.post_id, m.meta_key, m.meta_value
FROM wp_posts p, wp_postmeta m
WHERE p.ID = m.post_id
LIMIT 0,10;";

$result = $wpdb->get_results($sql);

foreach ($result as $topten) {
$postid = $topten->ID;
$title = $topten->post_title;
$commentcount = $topten->comment_count;
if ( $topten->meta_key == $custom_field_name) {
$img = '<img src="'.$topten->meta_value.'" alt=""/>';
<li><a href="<?php echo get_permalink($postid); ?>"><?php echo $img; ?></a></li>
<?php }

Once you saved the file, this will work perfectly. Notice that this code get thumbnails from the ten most commented posts, but you can easily modify the number of thumbnails to get: Edit the 0,10 in the sql query, replacing it by 0,3 to get images from the 3 most commented posts.

Your choice for site templates and wordpress themes


Got something to say?

You must be logged in to post a comment.