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;
}


Related articles:

Your choice for site templates and wordpress themes

Comments

6 Responses to “Get the first image from the wordpress post and display it”

  1. Oxygen Kiosk » Wordpress Post Image Resources on March 18th, 2009 9:07 am

    [...] 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. [...]

  2. Retrieve a Post’s First Image and Resize it with TimThumb | SpiderMarket on April 24th, 2009 12:30 pm

    [...] 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 [...]

  3. kellyapproved on June 1st, 2009 12:15 am

    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.

  4. Get the first image from the wordpress post and display it « rvwd.net on July 22nd, 2009 2:11 am

    [...] via [...]

  5. chedonline on December 4th, 2009 11:10 am

    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?

  6. tobe on January 30th, 2010 6:34 pm

    does not work. with my wordpress it always extracts last image, not first!
    can you help?

Got something to say?

You must be logged in to post a comment.