WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
Do you mean the first image uploaded to a post or the actual gallery shortcode. – Wyck Feb 5 '13 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.. – Andy Jonathan Feb 5 '13 at 19:43

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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