
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.

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
Great tip.. This will help me a lot as Im using a custom field..
Let me try this
Great recipe!
is it possibile to pass parameters to size the image?
Something like ?
echo catch _ that _ image (100,100)
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!
What a timing! I was just looking for something like this
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
Nice tip
how to make it click able image to the post itself ?
Thanks
Any help about my request?
Forget My Question, This function only get the URL of the image and this is what I really want.
Thanks
Great recipe!
Is it possible to pass parameters to size the image?
Something like?
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!
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″‘);
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″‘);
Great recipe!
is it possibile to pass parameters to size the image?
Something like ?
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?
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…
Perfect. This is going to be so useful in the themes I make.
Thank you…
Great tip. I always had to ask my brother to do all that for me – now I won’t need him
. Thanks.
thanks a lot this will come handy in my new under development design
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
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?
WOW, great tip I might try this once I put more images in my post.
Credit:
http://wordpress.org/support/topic/246893
Great idea, i will put this to my Blog
Great tip! And just in time for me to do some coding!
Cheers!
Great post. Now, how to automatically re-size and crop images on post teasers?
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.
Thnx Weston, I’ll try it now.
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
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?
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.
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
awesome ! i was looking for that from couple of days and glad that i got it from here . Thanks
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!
This is so simple I love it and it works outside the loop.
Is also possible display a video preview image ??
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
big thanks..
Words can’t explain how much I have been looking for something like this for nearly a year…thanks sooooooooooooo much!
nice tip, thanks for the tut..
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.
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;
}
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
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
@Marcoo Tubb:
An easy solution is to add if after the more tag. So the image won’t show up on the front page.
@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.
Hello, I need that this function embed the original width and eight of the image picked. How is possible to do this? Thanks!
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!!
Good hacks..
@weston deboer Thanx a lot for your help.
@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?
The code didnt display corectly
<img src="” alt=”" />
how to create .php file? sorry noob question
This one works really well.
Question:
How would you change it so that it gets the first image from the previous_post?
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
).
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.
Cheers it works a treat on my new blog site : )
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!
Thanks so much friend. Now i can forget custom fields to create the image.
Wow, the autobloggers will have a field day with this
This one is excellent tip. Thanks alot. Have to use it for a client project.
Thanks once again.
Trackbacks: