Post Pic

How to: Get the first image from the post and display it

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. Just read on.

First, paste this function on your functions.php file.

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

Once done, you can simply call the function within the loop to display the first image from the post:

<?php echo catch_that_image() ?>

112 Responses

Feb 25 2009 09:21

Great tip.. This will help me a lot as Im using a custom field..
Let me try this

Feb 25 2009 10:08

Great recipe!
is it possibile to pass parameters to size the image?
Something like ?

Feb 25 2009 10:10

echo catch _ that _ image (100,100)

Feb 25 2009 11:11

Great recipe! I’d be interested in a way to define the size of the images as well! Or maybe a way to display the thumbnail of the image only, instead of the complete original image!

Feb 25 2009 12:12

What a timing! I was just looking for something like this :)

Feb 25 2009 15:20

How to trow away the <img src bla bla?

I want get the URL of the image. (http://myurlimageblabla)
Any body can solve this dummy question?

Best Regards

Jauhari

Feb 25 2009 18:56

Nice tip

how to make it click able image to the post itself ?

Thanks

Feb 26 2009 13:02

Any help about my request?

Feb 26 2009 13:08

Forget My Question, This function only get the URL of the image and this is what I really want.

Thanks ;)

Feb 26 2009 14:19

Great recipe!
Is it possible to pass parameters to size the image?
Something like?

Feb 26 2009 20:19

I think you could make it click-able with the code below.

<a href="">

</code

You should be able to easily give the image a class and specify height through css.

Thanks for the tip Jean!

Feb 27 2009 06:22

This function return the first image of the post (even if it dont be on the content) the ’size’ parameter let you define the size of the image (thumbnail or medium) and the ‘add’ parameter add further parameters to the image tag, like class or width and height.

function the_thumb($size = “medium”, $add = “”)

{

global $wpdb, $post;

$thumb = $wpdb->get_row(“SELECT ID, post_title FROM {$wpdb->posts} WHERE post_parent = {$post->ID} AND post_mime_type LIKE ‘image%’ ORDER BY menu_order”);

if(!empty($thumb))

{

$image = image_downsize($thumb->ID, $size);

print “post_title}’ {$add} />”;

}

}

Ex. the_thumb(‘medium’, ‘class=”alignleft” width=”200″ height=”175″‘);

Feb 27 2009 06:32

This function return the first image of the post (even if it dont be on the content) the ’size’ parameter let you define the size of the image (thumbnail or medium) and the ‘add’ parameter add further parameters to the image tag, like class or width and height.

function the_thumb($size = “medium”, $add = “”) {
global $wpdb, $post;

$thumb = $wpdb->get_row(”SELECT ID, post_title FROM {$wpdb->posts} WHERE post_parent = {$post->ID} AND post_mime_type LIKE ‘image%’ ORDER BY menu_order”);

if(!empty($thumb)) {
$image = image_downsize($thumb->ID, $size);

print “<img src=’{$image[0]}’ alt=’{$thumb->post_title}’ {$add} >”;
}
}

Ex. the_thumb(’medium’, ‘class=”alignleft” width=”200″ height=”175″‘);

Feb 27 2009 09:31

Great recipe!
is it possibile to pass parameters to size the image?
Something like ?

Feb 28 2009 00:00

I cannot get this to work. When I put the code into the functions.php file I get this error.

Parse error: syntax error, unexpected T_FUNCTION in /home/fluid8/public_html/fluid09/wp-content/themes/wp-sanda/functions.php on line 25

What could be the problem?

Feb 28 2009 12:50

thanks. Simply a great tutorial. I don’t scale the image, I just use them as the background of a div. so just the bottom right corner of the image will be displayed in which one can put a small logo for the preview…

Mar 01 2009 07:30

Perfect. This is going to be so useful in the themes I make.

Mar 02 2009 02:08

Thank you… :)

Mar 02 2009 11:49

Great tip. I always had to ask my brother to do all that for me – now I won’t need him :) . Thanks.

Mar 04 2009 12:01

thanks a lot this will come handy in my new under development design :)

Mar 05 2009 03:59

First of all… Your tutorials have helped me a lot in customizing my theme… so thank you!

I do have a question.
I have a section of my blog that is populated by a plugin that imports content from RSS feeds from video streaming sites.

My regular posts have a custom field [image] that I use to generate thumbnails for each post. I use those thumbnails in the body of the post and in conjunction with a related posts plugin, to pull a list of related posts (but display them as a grid of thumbnails instead of a list of posts).

The posts that are generated by the plugin don’t get the [image] custom field assigned and therefore the grid of related posts can’t find a thumbnail to display.

Is there a way that I can have the thumbnail that is imported by the plugin from the RSS feed assigned to the custom field [image] for each particular post?

thanks
Sebastian

Mar 10 2009 16:10

Hi Marcelo Mesquita,

I’m having difficulty getting your code to return my thumbnails. Any suggestions or are their any dependencies? I’m not getting any php errors so at least that’s a start.

If I change

if(!empty($thumb))

to

if(empty($thumb))

it will return

in the generated html page so I guess it’s just not seeing any images associated with the posts?

Mar 10 2009 17:10

WOW, great tip I might try this once I put more images in my post.

Mar 10 2009 17:56
Mar 10 2009 18:27

Great idea, i will put this to my Blog

Mar 11 2009 01:32

Great tip! And just in time for me to do some coding!

Cheers!

Mar 11 2009 05:39

Great post. Now, how to automatically re-size and crop images on post teasers?

Mar 12 2009 17:47

To resize images i used timthumb which has image caching built in, so it doesn’t use to much resources. http://www.darrenhoyt.com/2008/04/02/timthumb-php-script-released/

just download timthumb upload it to your server and load it like this inside the loop:
<img src=”/thumb.php?src=&w=200&h=200zc=1″ alt=”"/>

where thumb.php is the location of timthumb.php and the w and h are the width and heights of the smaller image that you want it to be.

Mar 12 2009 18:21

Thnx Weston, I’ll try it now.

Mar 13 2009 18:02

Well, I saw this feature in one of a blog, I was searching for it on Google and at last found this article while stumbling.. Thanks for it :)

Mar 15 2009 02:57

Is anyone else having trouble using the image resizing script suggested by weston deboer along with this recipe? I haven’t been able to get timthumb.php to work with images that are addressed as anything but absolute paths. For example

`/images/image.gif` works with the script, while `http://www.site.com/images/image.gif` does not.

Is there a way to get catch_that_image to catch only the absolute path to the image?

Apr 16 2009 16:42

Wired – I am having a similar problem, I am installing catch_that_image on Wordpress MU which stores images in a different directory to normal wordpress.

Catch_that_image generates http://…/cms/files/2009/04/ which works to view the image but I need the full URL of : http://…/cms/wp-content/blogs.dir/2/files/2009/04/ if tomthumb to work. I’m not sure how to get it to do this.

Apr 19 2009 01:04

HI Jean
I have an issue whit this, so i’m doing like the tutorial but isn’t work, why? colud be ’cause it’s wp 2.7¿?, thanks for the help i was waiting for someting like this for a long time….thanks

Apr 19 2009 22:27

awesome ! i was looking for that from couple of days and glad that i got it from here . Thanks

May 03 2009 14:15

I’ve edited this recipe so that many calls to it from one page will not cripple my server :) Its on my website.

Btw thanks for the recipes! :)

May 31 2009 19:02

This is so simple I love it and it works outside the loop.

Jun 10 2009 00:33

Is also possible display a video preview image ??

Jun 10 2009 04:37

Amazing script, simple and did the job well. Thanks a lot, I was just looking for script to retrieve URL of 1st image in the post, and here I found ^^ Keep up the good sharing :)

Jun 15 2009 23:07

big thanks..

Jun 25 2009 05:45

Words can’t explain how much I have been looking for something like this for nearly a year…thanks sooooooooooooo much!

Aug 10 2009 19:16

nice tip, thanks for the tut..

Aug 12 2009 00:05

Wow. Amazing it is so simple. I have seen so many tutorials that just make it really confusing. Or plugins that I have to leave directories 777

First time visitor..New feed subscriber!

Thanks.

Sep 17 2009 20:16

Just tried to use this function on the front page and it didn’t work… for those looking for a fix this seemed for work for me although any hardened wordpress devs should glance an eye over it just incase I’m commiting a cardinal sin… either way, works nicely for me.

It just calls the post information for one post to the function which then allows the data to be extracted. I was going to replace $post->post_content with the_content() ; within a loop but it appears I didn’t need to.

——–

function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();

//THIS BIT WAS ADDED
query_posts(’showposts=1′);
the_post();

$output = preg_match_all(‘//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;
}

Sep 24 2009 16:54

Hi there,
love the post but can’t really get it to work…
the only thing that’s shown on the index page is the web URL, PLUS all the images from the post. I just want to first one to be displayed which this recipe seem to be all about. What am I doing wrong?

I would appreciate your help

Hampus

Oct 01 2009 22:27

Hey guys,
I was having a problem with the code. The code works perfectly but on my front page it displays both the post’s image and the thumbnail I am trying to create. Am I doing something wrong here?

I’d also like to say a quick thank you. Your articles have been a big help in producing my blog’s foundation.

Marco

Oct 02 2009 02:40

@Marcoo Tubb:

An easy solution is to add if after the more tag. So the image won’t show up on the front page.

Oct 02 2009 02:40

@Marcoo Tubb:

An easy solution is to add the image after the more tag. So the image won’t show up on the front page.

Oct 13 2009 16:08

Hello, I need that this function embed the original width and eight of the image picked. How is possible to do this? Thanks!

Oct 14 2009 22:49

Great tip!! I tried to use several plugins for this but they had too many options, and I only wanted to extract the image url so I could resize it using the timthumb script. And this worked perfectly. Just what I was looking for. Thank you!!

Oct 17 2009 15:28

Good hacks..

Oct 18 2009 09:10

@weston deboer Thanx a lot for your help.

Nov 01 2009 12:46

@Hampus: you should use this function like this:
<img src="http://” alt=”" />
because the function only extracts the src URL.

This function, or something similar should be coded inside Wordpress.
Don’t you all agree?

Nov 01 2009 12:55

The code didnt display corectly

<img src="” alt=”" />

Nov 17 2009 11:48

how to create .php file? sorry noob question

Dec 04 2009 05:22

This one works really well.

Question:

How would you change it so that it gets the first image from the previous_post?

Dec 14 2009 19:41

Thanks for nice hack! I was wondering if there’s any way to grab first image from post’s gallery instead of any first image in post. (Hope you get what I mean ;) ).

Dec 18 2009 16:53

this is me being a PHP fool, but is there a way to only get the first image from a post in a specific category? thanks for any clues.

Dec 19 2009 16:51

Cheers it works a treat on my new blog site : )

Dec 21 2009 04:18

thank you for posting this…
can i ask u something? i’m a newbie, and i’m making my own wordpress theme with this loop, and id like to see the title displayed before the image, how can i make it? i added the_title(); function before the image, but then the entries doesnt look aligned.
Thats my code (inside the loop):

<a href="” title=”" class=”img-loop”>
<img src="” alt=”"/>

thanks!

Dec 26 2009 16:25

Thanks so much friend. Now i can forget custom fields to create the image.

Dec 28 2009 19:05

Wow, the autobloggers will have a field day with this

Jan 22 2010 21:50

This one is excellent tip. Thanks alot. Have to use it for a client project.

Thanks once again.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required