Query posts only with featured image

The question:

I want to query 6 posts, but only those which have a featured image attached. I am using meta_key method for this with WP_Query as such:

$args = array(
    'post_type'  => 'post',
    'meta_key' => '_thumbnail_id',
    'post_count' => 6 );
$query = new WP_Query($args);

Followed by

<?php while($query->have_posts()) : $query->the_post(); ?>
    <h2><?php the_title(); ?></h2>
    <?php the_post_thumbnail('thumbnail'); ?>
<?php endwhile; ?>

This doesn’t seem to work. The query is returning more than 6 posts and also those which don’t have a featured image. Any ideas what I’ve got wrong here?

@chip: var_dump($query); gives a large result so I have posted it in a pastebin

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

When running the importer, you must check the checkbox to download and import all media/attachments, and the original server must be reachable from the server conducting the import.

If you fail to do this, the posts will have no valid featured image, and fail to show in your loop, and any attempt to call the_post_thumbnail will fail giving the impression they have no featured image.

To fix this, delete your posts, and re-import using the correct settings, making sure the old server is still accessible at its original URL.

Also to demonstrate the point, you made no attempt to actually check the posts, always check e.g.:

if ( $query->have_posts() ) { // you never checked to see if no posts were found
    while($query->have_posts()) { // alt style syntax doesn't work with most IDEs
        // individual statement should be on individual line

        // you only need open/close tags here, not every line, save yourself some time typing
        ?><h2><?php the_title(); ?></h2><?php 

        // only print out the thumbnail if it actually has one
        if ( has_post_thumbnail() ) {
            echo '<p>post says it has a featured image</p>'; // double checking
        } else {
            echo '<p>this post does not have a featured image</p>';
} else {
    echo '<p>no posts found</p>';

If you have not checked the checkbox, you will get images saying they have a featured image, but no image is shown

Method 2

As of WordPress 3.5, the Meta Query Parameters support EXISTS and NOT EXISTS as compare operators. In the case where you are using these, you can omit the value part of the meta query. Try the following arguments for your query:

$args = array(
   'post_type'  => 'post',
   'posts_per_page' => 6,
    'meta_query' => array(
         'key' => '_thumbnail_id',
         'compare' => 'EXISTS'

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment