Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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 = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];

if(empty($first_img)){
$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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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].

EDIT:

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.

share|improve this answer
    
that works great. thanks! –  zac May 6 '11 at 6:50

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

share|improve this answer
    
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 '11 at 19:40

Your Answer

 
discard

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.