How to Get the First Three Images Attached to a WordPress Post

I had a situation where I wanted to snag the first three images in a WordPress post and display them elsewhere. I found a bunch of information, in both the WordPress forums and Codex, but it either didn’t work, or was really slow loading.

So I came up with more or less my own solution based on one provided by jocken on the support forums.

function get_three_wordpress_attachment_images($size = thumbnail) {
if($images = get_posts(array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => 3,
'post_status' => null,
'post_mime_type' => 'image',
))) {
foreach($images as $image) {
$whatimage = wp_get_attachment_image_src($image->ID,'thumb');
$whatimage = $whatimage[0];
$attimg = '<a class="image-previews" href="'.get_permalink().'" style="background-image:url('.$whatimage.')"></a>';
echo $attimg;
}
}
}

Then you can just do <?php get_three_wordpress_attachment_images(); ?> to display them.

The main difference here is that his, which works and does the job perfectly well, is that I have mine setup so that I could wrap the images in a link (to the original post they’re associated with), and I wasn’t concerned about the order the images appeared in.

You can change 'numberposts' => 3, to any number you’d like, and that’s how many images will show up.

Up Next: More Updates from Google Regarding Mobile and How Search Results are Displayed