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="https://wordpress.stackexchange.com/questions/22001/<?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="https://wordpress.stackexchange.com/questions/22001/$image_img_tag[0]">";
} ?>

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

Here is the paste of the page

1 Answer
1

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>

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *