Get the first image from the wordpress post and display it
February 25, 2009 · Print This Article
Most WordPress users are using custom fields to display thumbs on their blog homepage.
It is a good idea, but do you know that with a simple php function, you can grab the first image from the post, and display it.
You can simply call the function within the loop to display the first image from the post:
<?php echo get_first_image() ?>
But first, paste this function follow on your functions.php file.
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i’, $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = “/images/default.jpg”;
}
return $first_img;
}





















[...] Get the first image from the wordpress post and display it: Requires some functions.php hacking, searches the actual post text, and has the advantage of getting the first actual image in the post, rather than the first image uploaded and associated with the post. [...]
[...] found a bunch of articles with code samples and one plugin: Simple Image Grabber, WordPress Forum, Live Experience, WP Recipes, and Justin Tadlock. In nearly every set of comments, people were trying to figure out [...]
Unfortunately, I never used the custom field when I did my posting, so unless I go back to every post, I’m hoping this code will help me.
Would you know how I could use this code to display images with my recent posts as well as with related posts.
[...] via [...]
Great function. It works like a charm. I have a question:
How would you return the first image from the previous_post or next_post?
does not work. with my wordpress it always extracts last image, not first!
can you help?
how can i display last 5 images?? or last 5 images with posts??
[...] Copy this function to your functions.php file, and call from where ever you like (Code from: livexp). [...]