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.
<ul>
<?php
//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 }
}
?>
</ul>
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.
Leave a Comment