How to query posts that have post thumbnail

If you want to fetch posts with thumbnail images there’s a simple trick you can use on your WP query.  The trick is to include this simple line of code in your $args array:

'meta_key'    => '_thumbnail_id'

Let’s say you want the last 8 published posts that have a featured image set.  Simply set your arguments like this and wordpress will do the magic:

$args = array(
 'post_type' => 'post',
 'order' => 'DESC',
 'orderby' => 'date',
 'post_status'=>'publish',
 'posts_per_page' => 8, 
 'meta_key' => '_thumbnail_id'
);

This trick will allow you to only show posts that have featured image attached to them in your site.  May be useful for a homepage where you want to always have a few graphics filling the fold.

Leave a Reply