Warning: include(/home/185104/domains/s185104.gridserver.com/html/wp-content/plugins/wp-synhighlight/object.php): failed to open stream: No such file or directory in /nfs/c06/h04/mnt/185104/domains/tommaitland.net/html/wp-config.php on line 42

Warning: include(): Failed opening '/home/185104/domains/s185104.gridserver.com/html/wp-content/plugins/wp-synhighlight/object.php' for inclusion (include_path='.:/usr/local/php-5.6.21/share/pear') in /nfs/c06/h04/mnt/185104/domains/tommaitland.net/html/wp-config.php on line 42
Display All Images Attached to a Post in WordPress - Tom Maitland

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”]

<?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>';
}

[/codesyntax]

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.