get first image thumbnail from wordpress post

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

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

4 thoughts on “get first image thumbnail from wordpress post”

  1. Thanks for this post, i’m unable to get it working though. After trying several tutorials on using the first post image for thumbnail. This one just doesn’t display anything at all, no errors, but no image.
    I added the line to the loop, no idea why it’s not showing anything though >.<

  2. I’m unable to get this to display the thumbnail at all, I’m sure I’ve added it properly. I’ve added thumbnail support and after doing that it displays the same image on every post. Any suggestions?

  3. Hi
    I love the post. and used it in my Website.

    But this function doesn’t save the image in the database in defined size, it just scales down the image size every time a page is loaded. and this causes to lower page loads.

    Can you make it to save the image in that defined sizes and call the function.

    If you can. It would be of great help.

Leave a Reply

Your email address will not be published.