I have already mentioned a few ways to do this but I have discovered a few problems with my old code. I have improved this one quite a bit so I felt that I should just delete my old suggestions and offer you the best technique I have discovered.

The whole point of this piece of code is to make it easier for people to retrieve images from their posts. If you want to pull only the excerpt but also want to display an image along side it, this code is all you need. Forget using custom fields or plugins, just add this code to your theme’s functions.php and then call the function within the loop to pull the image you want.

It functions by going through your post’s content and placing every image it encounters into an array. You can then use the function to call any image our of that array and display it.

If you already have a functions.php file in your theme’s folder, just place the following code between the opening <?php and closing ?> tags. If not, create one and make sure to add an opening <?php and closing ?> tag.

function getImage($num) {
global $more;
$more = 1;
$link = get_permalink();
$content = get_the_content();
$count = substr_count($content, '<img');
$start = 0;
for($i=1;$i<=$count;$i++) {
$imgBeg = strpos($content, '<img', $start);
$post = substr($content, $imgBeg);
$imgEnd = strpos($post, '>');
$postOutput = substr($post, 0, $imgEnd+1);
$postOutput = preg_replace('/width="([0-9]*)" height="([0-9]*)"/', '',$postOutput);;
$image[$i] = $postOutput;
if(stristr($image[$num],'<img')) { echo '<a href="'.$link.'">'.$image[$num]."</a>"; }
$more = 0;

Now whenever you want to display an image from a post, just use <?php getImage('1'); ?>. The number ’1′ can be changed to any number. If you want to pull the second image from your post, change it to ’2′ and so on. Be sure to place this within the loop so that is works properly.

NOTE: I just created a plugin for this called Simple Image Grabber.