WordPress Tip: Automatically Pulling Images from Posts

I wanted to share with you a brilliant piece of code I found for pulling images from posts.
On this site, you’ll see that I use image thumbnails on the blog homepage. Normally I’d use a custom field to link the image but I what I really wanted was a way to pull in the one wordpress generates according to your options in the media settings.
Luckily I found it via a forum post by endortrails.
To use it first paste this code into your functions.php file:
[php]
function postimage($size=medium) {
if ( $images = get_children(array(
‘post_parent’ => get_the_ID(),
‘post_type’ => ‘attachment’,
‘numberposts’ => 1,
‘post_mime_type’ => ‘image’,)))
{
foreach( $images as $image ) {
$attachmenturl=wp_get_attachment_url($image->ID);
$attachmentimage=wp_get_attachment_image( $image->ID, $size );
$imagelink=get_permalink($image->post_parent);
echo ‘<a href="’.$imagelink.’">’.$attachmentimage.apply_filters(‘the_title’, $parent->post_title).’</a>’;
}
}
}
[/php]
Then in your theme template you use:
[php]
<?php postimage(‘thumbnail’); ?>
[/php]
when you need the thumbnail url (remembering to wrap in php tags). You can also use:
[php]
<?php postimage(‘medium’); ?>
<?php postimage(‘large’); ?>
[/php]
for the other sizes wordpress generates as well. Note that these will only pull the first image from a post and only when you have uploaded it (so it appears in that posts image gallery).
Got any wordpress tips? Share them in the comments below.
5 Aug 09 at 5:03 am
I’ve been looking for this everywhere, Thank you. We shall see how it works…
5 Aug 09 at 7:37 am
Glad I could help. Let me know here if you have any probs
5 Aug 09 at 11:46 pm
Hey Chris, I’m having problems getting this working. Does it have to be inside the loop? Because I am building a dynamic, featured content slider, and it is not displaying any images….Help?!
5 Aug 09 at 7:12 am
That’s right yes it must be inserted into the loop.
Is it just not displaying at all or are you getting an error?
5 Aug 09 at 6:00 pm
How would you change this code if you wanted all the (first) images from posts contained in a specified category to be displayed?