4

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.

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>
5

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.

  • ok great it worked out for you, good luck with your project. – birgire May 24 '13 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.