1

First, I need to ask if it's possible to create a photo gallery only with the featured images of the latest 6 posts? I assume it is possible but just want to make sure.

I don't have much experience working directly with the wordpress gallery so could someone point me in the right direction for accomplishing this? Any plugin with similar functionally or tutorial will do.

2
$query = new WP_Query(array('posts_per_page' => 6, 'meta_key' => '_thumbnail_id'));
while($query->have_posts()) :
    $query->the_post();
    the_post_thumbnail();
endwhile;

This code gets 6 latest posts which have featured image available & show those 6 images on the page. It will skip those posts where there is no featured image set even if they are newer.

This will probably get you started. You should read the codex pages for WP_Query & the_post_thumbnail

1
  • Thanks for helping! Will test the code and read the codex. Oct 19 '12 at 19:39
3

As I just ran into that problem yesterday, here's the solution: You'll have to set numberposts as well as posts_per_page to cover every edge case scenario.

I also included the possibility to query for attached files as well as a check if there're any attachments.

$wpse69856_query = new WP_Query( array(
     'posts_per_page' => 6
    ,'numberposts'    => 6
    ,'meta_key'       => '_thumbnail_id'
    // For non-featured images
    ,'meta_key'       => '_wp_attached_file'
) );
if ( $wpse69856_query->have_posts() )
{
    while( $wpse69856_query->have_posts() )
    {
        $wpse69856_query->the_post();
        the_post_thumbnail();
    }
}

Note: This is just an addition to @Mridul Aggarwal answer to make it more complete. In the case this works for you, please mark his answer as solution. Thanks.

3
  • thanks for your input. One small question though: I don't understand the use of numberposts, could you please explain a bit? Oct 19 '12 at 20:15
  • @MridulAggarwal To be honest, I don't remember it - currently wresting with a new server and dozens of other things. As far as I can remember, the one takes only the current page in account (affected by pagination) and the other one takes all posts. But I can also be wrong on this issue. I just dumped both queries on 'posts_clauses' to get the pieces and 'posts_request' to get the final query string and then inspected the result. There was also some other plugin of mine interfering, so as I said: I can also be wrong in this case :)
    – kaiser
    Oct 19 '12 at 20:24
  • Thanks to both of you for helping. Mridul code works, now I just need to customize it a bit and probably include it in a widget. Oct 20 '12 at 11:54

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.