Get Post’s first image using Short-code

I would rewrite a simple shortcode to retrieve only post images:

add_shortcode( "postImages", "stack_309224_attachhment" );

function stack_309224_attachhment($atts){
extract(shortcode_atts( array(
  'id'      => 1, // default id of the post
  "max"   =>4 ,// default max number of images to display
  "featured"=>"false" // if to retrieve the post featured image or not, default false
),  $atts ));

ob_start();
if($atts['featured']=="true"){ // display only the featured image
  ?>
  <figure><img src="https://wordpress.stackexchange.com/questions/309224/<?php echo wp_get_attachment_image_src(get_post_thumbnail_id( (int)$atts["id']) )[0]?>" /></figure>
  <?php
}
else{ // display a gallery of attached images within  "max" attr.
  $images=get_attached_media( 'image', (int)$atts['id'] );
  if(count($images) > 0 ){
   ?>
   <div class="gallery">
   <?php
   $index=0;
   foreach($images as $image){
     if($index < (int)$atts['max']){ //display image only if within max 
    ?>
    <figure><img src="<?php echo wp_get_attachment_url($image->ID)?>" /></figure>
    <?php
      $index ++;
     }
   }
 ?></div><?php
 }     
}
return ob_get_clean();
}

Then in the wp editor you can use:

  • [postImages id=2387 featured=”true”] -> displays only featured image for post #2387

  • [postImages id=2387 max = 4] -> displays a gallery of 4 images attached to post #2387