Help with a random image widget.

Hi,

Most (but not all) of my posts have a nice handcrafted 150x75px thumbnail as a featured image. I’m using the code below to show a set of those featured image thumbnails in my side bar, such that clicking on the thumbnail takes you to the post.

[php]

<?php $thumbnails = get_posts('numberposts=10&orderby=rand'); foreach ($thumbnails as $thumbnail) { if ( has_post_thumbnail($thumbnail->ID)) { echo ''; echo get_the_post_thumbnail($thumbnail->ID, 'thumbnail'); echo ''; } } ?>[/php]

This code would be perfect if every post had an image, but as it stands, if a post doesn’t have a featured image this code will still include it in its list of source images to pick from - and return an ‘empty’ image. If theres 4 posts without featured images, I can get back 4 blank lines and 6 pictures for my random set of 10

How could the code be altered so that it only picks posts that have a featured image, and so always gives me the needed 10 images?

(I know nothing about php - that code was given to me, so please keep it very simple! )

Thank you :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service