Query only posts with thumbnails

The issue with the coide for displaying only posts with thumbnails in the past has been that you query the posts type and then put a ‘if has post thumbnail’ conditional in the loop. This means that if you wanted 12 posts and that how many you get in the query, maybe only 6 have thumbnails/featured images.
Then you only display 6 – not the 12 you were after.

A comment posted on this WordPress support thread solves that problem.

following the docu from ‘has_post_thumbnail()’ to this:
http://phpxref.ftwr.co.uk/wordpress/wp-includes/post-thumbnail-template.php.source.html#l25

shows that the thumbnails are stored in a custom field with the key ‘_thumbnail_id’

then use the custom field parameter of query_posts()
http://codex.wordpress.org/Function_Reference/query_posts#Custom_Field_Parameters

query to get only posts with thumbnail:

<pre><code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; // pagination

$args = array(
'posts_per_page' => -1, // optional to overwrite the dashboard setting
'paged' => $paged,
'meta_key' => '_thumbnail_id'
);
query_posts($args); 	?></code></pre>

Revisions

There are no revisions for this post.

Tags: , ,

No comments yet.

Leave a Reply