Monday, 16 April 2012

WordPress - Display All Images Associated with Page



This is a code snippet I use quite often to display custom galleries in my themes. Paste the following code within the loop of your page template.
1echo '<ul id="Thumbnails">';
2
3$args = array( 'post_type' => 'attachment', 'numberposts' => -1,'post_status' => null, 'post_parent' => $post->ID );
4$attachments = get_posts($args);
5if ($attachments) {
6foreach ( $attachments as $attachment ) {
7
8$image_attributes   = wp_get_attachment_image_src( $attachment->ID ); // returns an array
9$imgTitle           = $attachment->post_title;
10$imgCaption         = $attachment->post_excerpt;
11$imgDescription     = $attachment->post_content;
12
13echo '<li><a href="' . $attachment->guid . '"><img ';
14
15if ( $attachment->post_name == $_GET['image'] ) { echo 'class="active"'; }
16
17echo ' src="' . $attachment->guid . '" title="' . $imgCaption . '" alt="' . $imgTitle . ' - ' . $imgDescription . '"  /></a></li>' . "\n";
18
19}
20}
21
22echo '</ul>' . "\n";
23echo '<div style="clear: both;"></div>';