Pull images from the gallery

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?

Read More

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.

Related posts

Leave a Reply

2 comments

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