I am looking for a simple PHP function to insert the first image from the gallery into the post, full width (I am using custom post types btw). So the syntax will be:

<img src="xxxxx" />

any ideas?

many thanks Andy

  • Do you mean the first image uploaded to a post or the actual gallery shortcode.
    – Wyck
    Commented Feb 5, 2013 at 19:39
  • the first image uploaded to a post... I dont think i can use the gallery shortcode to insert an image without knowing the attachment ID.. Commented Feb 5, 2013 at 19:43

1 Answer 1


This is the function I use, maybe there is a better way.

$attachments = get_children(
                                  'numberposts' => -1,
                                  'order'=> 'ASC',
                                  'post_mime_type' => 'image',
                                  'post_parent' => get_the_ID(),
                                  'post_type' => 'attachment'

               $first_attachment = reset($attachments);
               //$last_attachment  = end($attachments); or last image
               echo wp_get_attachment_image($first_attachment->ID, 'full');

Additional wp_get_attachment_image parameters found here: http://codex.wordpress.org/Function_Reference/wp_get_attachment_image

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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