Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have a function get_images() in which I would like to display all image attachments for the current post (or page) in a list with the last image having a class="last" attribute to mark it as the last image in the list.

The code below is my first pass at getting the attached images to display, however, its only listing one image out of the loop so my foreach is botched...

function get_images() {
  global $post;
  $attachment = array_values(get_children(array( 
    'post_parent' => $post->ID, 
    'post_type' => 'attachment', 
    'post_mime_type' => 'image', 
    'order' => 'ASC', 
    'numberposts' => 1 
  )));
  if ( $attachment ) {
    foreach($attachment as $attachmentImage) {
      echo '<img src="' . wp_get_attachment_url($attachmentImage->ID) . 
        '" class="post-attachment" />';
    }
  }
}
share|improve this question

1 Answer 1

up vote 1 down vote accepted

This should do it, I think:

function get_images() {
  global $post;
  $attachment = get_children(array( 
      'post_parent' => $post->ID, 
      'post_type' => 'attachment', 
      'post_mime_type' => 'image', 
      'order' => 'ASC', 
      'numberposts'  => -1 ), 
    ARRAY_N );
  if ( $attachment ) {
    $attachment_count = count($attachment);
    foreach($i=0; $i < $attachment_count; $i++) {
      $last = ($i == ($attachment_count-1) ) ? ' last' : '';
      echo '<img src="' . wp_get_attachment_url($attachment[$i]->ID) . 
        '" class="post-attachment'.$last.'" />';
    }
  }
}
share|improve this answer
    
How this can be applied to the pages? I want to show all page attachments in custom template, but it uses all attached images from all posts as well. –  Dmitry Nov 7 '10 at 14:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.