I am building a template where wordpress is being used primarily as an image CMS, I am pulling the first image from the content section of each post.

<img src="<?php echo grab_image() ?>" />

function grab_image() {
global $post, $posts;
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

$first_img = "";
return $first_img;

My question is how can I, instead of grabbing it from post_content, grab the first image from the uploaded image gallery?

So, the process to add an image would be to upload and then exit out (without inserting into post). I dont know what you call this or what to look for.. attachments? media library? The content area would be used strictly for text along with any extra meta boxes.

2 Answers 2


Use get_children() (Codex ref):

$images = get_children( array( 
     'post_parent' => $post->ID, 
     'post_type' => 'attachment', 
     'post_mime_type' => 'image', 
     'orderby' => 'menu_order', 
     'order' => 'ASC' 
) );

The first image will be $images[0].


And by "first image", I mean, the $ID of the first image, which you can use with any of the myriad image- and attachment-handling functions in WordPress. If you can clarify what you want to do with the image, I can provide more specific, further instruction.


Maybe you'd like to make a photoblog with YAPB and the reflection theme

  • Thanks for the suggestion.. YAPB is pretty neat but I am creating my own template with a lot of custom functionality and do not want to use any plugins.
    – zac
    May 3, 2011 at 19:40

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.