Skip posts without a thumbnail in loop

I want skip every post that has no thumbnail. The code does not work properly yet.

Actually the script doesn’t show posts without a thumbnail – that’s good, but in the loop the post with no thumbnail is still counted as a post.

Read More

So when I have for example 10 posts in my database. I want show 5 of them. But only the posts with a thumbnail.

<ul>

    <?php

    $args = array(  'numberposts'  => 5,  
                    'orderby'      => 'date',  
                    'order'        => 'DESC',
                    'post_type'    => 'post',
                    'post_status'  => 'publish' 
                );

    $my_posts = get_posts( $args );
    global $post;
    foreach( $my_posts as $post ) : setup_postdata($post); 

    if ( !has_post_thumbnail() ) { 
        continue;             
    } else {

    ?>

        <li>
            <div class="clearfix" >
                <div class="thumb"><?php the_post_thumbnail('post-image-big'); ?></div>
                <a href="<?php the_permalink(); ?>" class="title"><?php the_title(); ?></a>
                <p class="category"><?php the_category(', '); ?></p>
            </div>
        </li>

    <?php } ?>

    <?php endforeach; ?>

</ul>

Related posts

1 comment

  1. You can try to add

                    'meta_key'     => '_thumbnail_id',
    

    to your input arguments:

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

    to query only posts with thumbnails (i.e. featured images).

    ps: instead of this structure:

    if ( !has_post_thumbnail() ) { 
            continue;             
    } else {
    
    }
    

    you can in general use

    if ( has_post_thumbnail() ) { 
    
    }
    

    But you can now skip the if-sentence part in the loop since you are now only fetching posts with featured images.

Comments are closed.