Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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>
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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.

share|improve this answer
    
It works - Thank you. –  user2416687 May 24 '13 at 9:08
    
ok great it worked out for you, good luck with your project. –  birgire May 24 '13 at 9:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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