June 22 2012

WordPress function to retrieve first image

I needed to easily get the first image in a post. There is a native function calledĀ the_post_thumbnail(); , but it does not work in all situations. I wrote the following function in functions.php in the theme folder:

[sourcecode language="php"]
function azva_first_image($postID, $format) {
$args = array( 'post_type' => 'attachment',
'order' => 'ASC',
'orderby' => 'menu_order',
'numberposts' => 1,
'post_status' => null,
'post_parent' => $postID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ( $attachments as $attachment ) {
echo wp_get_attachment_image( $attachment->ID, $format );
}
}
}
[/sourcecode]

And use it by calling this code:

[sourcecode language="html"]
ID, 'little-square'); ?>
[/sourcecode]

Where Ā“little-square' stands, you can use any of the image_size present in the same functions.php file.