Tom Maitland

Creates digital things at Agency. WordPress developer. Web designer. Communicates for UN Youth Australia.

Display All Images Attached to a Post in WordPress

27 October 2012

I came across an issue for a site today where I wanted to display a ‘gallery excerpt’ for Gallery posts.

Letting the entire gallery through means (potentially) 100s of images loading on an index page, definitely not ideal visually or for page load. I gave the ‘Gallery Excerpt’ plugin a shot, but it doesn’t actually stop images being loaded – rather it just hides them with really poorly written markup.

The solution was instead to pull the first few images attached to the post and display them as the excerpt. Here’s the code to include in your theme:

[codesyntax lang=”php”]

$gallery = get_children( 'posts_per_page=5&post_type=attachment&post_mime_type=image&post_parent=' . $post->ID );
$attr = array(
    'class' => "attachment-$size wp-post-image",
foreach( $gallery as $image ) {
     echo '<a href="' . wp_get_attachment_url($image->ID) . '" rel="gallery-' . get_the_ID() . '">';
     echo wp_get_attachment_image($image->ID, 'thumbnail', false, $attr);
     echo '</a>';


Of course feel free to change the markup that is echoed out specific to your styling and for more or less photos adjust posts_per_page on the second line.