2

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" />';
    }
  }
}
1

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.'" />';
    }
  }
}
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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