2

I am grabbing an image that is uploaded to that post working with this function: wp_get_attachment_image_src

<?php 
    $images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC', 'numberposts' => 2 ) );
    if ( $images ) :
            $total_images = count( $images );
            $image = array_shift( $images );
            $image_img_tag = wp_get_attachment_image_src( $image->ID, 'full' ); 
                ?>

    <div class="two_images">
        <img src="<?php echo $image_img_tag[0] ?>">
    </div>

How do I grab the first two images that are uploaded to a post? I guess I need help with a foreach statement.. and limit it to two. I tried this but it just printed the same first image over and over..

<?php foreach ($image as $images) { 
         echo "<img src='$image_img_tag[0]'>";
} ?>

IF I echo $total_images then I get the correct count of 2

Here is the paste of the page

  • do you want the first two images uploaded or the first two images in the image order as set in the gallery tab? – Paul Sheldrake Jul 5 '11 at 7:55
  • The image order from the gallery tab! – zac Jul 5 '11 at 8:29
  • ! because I did not realize that was an option. – zac Jul 5 '11 at 8:31
4

Looks like you may have just not had a loop setup, try this one

<div class="two_images">
<?php
  global $post;
  $args = array( 
    'post_parent' => $post->ID, 
    'post_type' => 'attachment', 
    'post_mime_type' => 'image', 
    'orderby' => 'menu_order', 
    'order' => 'ASC', 
    'numberposts' => 2 );
   $images = get_posts($args);
   if ( $images ) {
    $i = 0;
    while($i <= 1){
      echo wp_get_attachment_image( $images[$i]->ID, 'full' );
      $i++;
    }
  }
?>
</div>
| improve this answer | |
  • thanks, but that doesnt work for me – zac Jul 6 '11 at 11:46
  • updated, should work this time – Paul Sheldrake Jul 6 '11 at 12:09

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.