get first image thumbnail from wordpress post

Most WordPress theme are using custom fields to display thumbs on their blog homepage. How to get first image thumbnail from wordpress post

get first image thumbnail from wordpress post

But you can take easily extract the first image from the post, and display the image as post thumbnail.

Just copy paste the following function in your functions.php file.


function get_first_image($id) {
$PostID = $id;
$all_images =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $PostID );

if($all_images) {

$arr_of_all_images = array_keys($all_images);

// Get the first image attachment from post
$firstImage = $arr_of_all_images[0];

// Get the thumbnail url for the attachment
// If you want the full-size image instead of the thumbnail, use wp_get_attachment_url() instead of wp_get_attachment_thumb_url().
$thumb_url = wp_get_attachment_thumb_url($firstImage);

// Build the <img> string
$First_thumb_image = '<a href="' . get_permalink() . '">' .
'src="' . $thumb_url . '" width="150" height="150" alt="Thumbnail Image" title="Thumbnail Image" />' .
'</a>';

// Print the thum image form post
echo $First_thumb_image;
}
}

You can call above “get_first_image” function anywhere in your post loop. I loop you need to just copy paste the following lines
to print the first image of post body.

<!--?php get_first_image($post--->ID);  ?>
get first image thumbnail from wordpress post

get first image thumbnail from wordpress post

Follwing article I found useful

http://codex.wordpress.org/Plugin_API/Filter_Reference

http://codex.wordpress.org/Function_Reference/wp_get_attachment_thumb_url

4 Comments

Add a Comment

Your email address will not be published. Required fields are marked *