How To Extract an Image Form a WordPress Post

Sometime, to make an archive page to look better, one needs to extract the first image of a post. With “first image” I mean the first image inserted in the gallery. Doing the trick is really easy.

First we need a function that extract the image. The function has to be called inside the “loop”:

function ximage($size='thumbnail') {
 global $post;
 $attachments = get_children(array('post_parent'=>$post->ID, 'post_status'=>'inherit', 
    'post_type'=>'attachment', 'post_mime_type'=>'image', 'order'=>'ASC', 'orderby'=>'menu_order ID' ) );

 if (empty($attachments)) return null;

 foreach ($attachments as $id=>$attachment) {
 $image = wp_get_attachment_image_src($id, $size);
 return $image[0];
 }
}

Then we can modify the “loop” (I’m using the new WordPress default theme, twentyten) which is in the file “loop.php”:

 <?php $img = ximage(); ?>
 <?php if ($img != null) { ?>
 <img src="<?php echo $img; ?>" height="150" width="150" align="left" style="margin-right: 10px;"/>
 <?php } ?>
 <?php the_excerpt(); ?>
 <br clear="all"/>    

(search “excerpt” to find where the code should be changed). The result? If still active you can see it on www.satollo.com.

Subscribe to my newsletter (but only if you're interested about WP and plugins)

Similar Posts

2 Comments

  1. Hi there. I recently was tasked with an assignment of extracting an image from a WordPress post and placing said image in the header of the site. After scouring the web, I have come across several different options of extracting the first image from the most recent post (which seems to work just fine). The problem is that I need to drill down. I need to extract the first image from the most recent post IN A SPECIFIC CATEGORY. The code I have starts in the functions.php page and is as follows (bear in mind that I am a PHP neophyte):

    function ximage($size=’thumbnail’) {
    global $post;
    $attachments = get_children(array(‘post_parent’=>$post->ID, ‘post_status’=>’inherit’,
    ‘post_type’=>’attachment’, ‘post_mime_type’=>’image’, ‘order’=>’ASC’, ‘orderby’=>’menu_order ID’ ) );
    if (empty($attachments)) return null;
    foreach ($attachments as $id=>$attachment) {
    $image = wp_get_attachment_image_src($id, $size);
    return $image[0];
    }
    }

    I then place the following in the header.php page where I want the image to appear:

    <img src="” height=”150″ width=”150″ align=”left” style=”margin-right: 10px;”/>

    The above code will place an image in the header that mirrors the first image from the most recent post. But just to reiterate, I need it do more than that – I need it to mirror the first image from the most recent post of a specific category. Any suggestions/solutions you have to make this happen are greatly appreciated (and if that means scrapping what I have and starting over, I am completely open to that).

Leave a Reply