DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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() ?>

69 Comments

  1. I use this function all the time on my sites, works great!
    Do you know if there is a way to get the first img from a gallery?

  2. I tried this and it only returned this text:

    /images/default.jpg

    Any ideas how to fix this?

  3. This works fine until you into a post with a video like you tube and then it shows a broken link.

  4. How would you return the ‘medium’ size version of the image? Seems like you would have to change the “return” method of display…

    Any ideas? Thanks.

  5. Since this question is being asked a lot; I edited the codex and added an example of how to get the first image associated with a post
    http://codex.wordpress.org/Function_Reference/get_children#Show_the_first_image_associated_with_the_post

  6. How can I get more than just the first image?

  7. This works brilliantly except for the fact that when the code is in functions.php I cannot logon to the dashboard!

    Any ideas???
    Thanks
    Vern

  8. Have partially answered my question! I am using this coding to extract the first image from a post to display on a webpage in my website (not a WordPress blog). So, instead of adding the php coding into the functions.php file in my theme, I have placed it in the php on my webpage.
    RESULT!

  9. would it be difficult to implement timthumb with this function?

  10. Great you saved my day. Can you tell me how to apply WordPress default thumbnail size to the first image?. Right now I am re-sizing the image using css. This makes the first image looks distorted. But the featured image appears fine. Please help me out. thanks in advance.

  11. Hi logesh, take a look here:

    // get the first image attached to the current post
    function aldenta_get_post_image($size = ‘thumbnail’) {
    global $post;

    $photos = get_children( array(‘post_parent’ => $post->ID, ‘post_status’ => ‘inherit’, ‘post_type’ => ‘attachment’, ‘post_mime_type’ => ‘image’, ‘order’ => ‘ASC’, ‘orderby’ => ‘menu_order ID’) );

    if ($photos) {
    $photo = array_shift($photos);
    return wp_get_attachment_image($photo->ID, $size);
    }

    return false;
    }

    // the html tag for the first image or false if no image is found
    $photo = aldenta_get_post_image();

    // end

    more about this you will find here:
    http://johnford.is/programmatically-pull-attachments-from-wordpress-posts

    hope that helped as it did for me.

  12. @Daniel I owe you a million thanks. It works like a charm. šŸ™‚

  13. My theme (premium theme and purchased by themify) supports featured image but it creates another problems. If I don’t use featured image option in posts, homepage does not show images with the post meanwhile if I used featured post utility in post it shows single photo two times.

    Can you help me how I can sort out this problem.

    with thanks and regards,

    Sunil

  14. Thanks a lot! i’m using this script for the new template that i’m developing!

  15. The code works fine but if you want to display the caption of the image?
    Do you have any hint (something to add to the code) so it displays the central caption of the image rather than displaying thumbnail, full size or the distorted size?

  16. MY Mistake – I meant clipping an image not caption.

  17. Anyway this could work with pages? I want to get the first image of a specific page.

  18. Hi, Does Jean-Baptiste, or Daniel, or anyone know how to limit the posts population? Instead of getting the FIRST image of ANY post, getting a RANDOM image of specific posts only?!

    I have “parent” posts with images on them (one of them I’d like to show, from x random posts) and “child” posts with images on them (which I don’t want to show).

    I am not a php programmer. I thought maybe the line “global $post, $posts;” is the problem in my case? Instead I’d need a base population of posts that’s limited to my “parent” posts. One way to do this would be to use custom fields, and mark each “parent” post. But even IF I knew how to do that, I don’t know what the php code must look like? Can anyone help?

  19. Hello, any chance you can tell me how to pull this image to another php page that will be displaying multiple blogs. The page I’m pulling to is on the same domain.. just pulling multiple blogs to one index.php. Please help!

  20. Hi,

    Does anyone know how I could use this in JS rather than PHP? I’m currently making an XML feed app using Phonegap and would like to bring back the first image to use as a thumbnail in my list. The feed is generated from posts on a WordPress site.

    Thanks,

  21. Hello,
    if you turn on the WP_Debug you will receive an Undefined offset 0 error on the line were this code 7 where this code is written : $first_img = $matches [1] [0];

    is their any possible way to solve it, because my theme is not getting accepted in WordPress Respiratory because of that error.

  22. How to get the second, third, fourth and fifth image?

  23. To get next image, just change $matches [1] [0]; to $matches [1] [1]; or $matches [1] [2]; and so on.

  24. Does anyone know how to show the image as a particular size?

  25. Hi Daniel, really impressed with your efoort by helping all, thankss, i’ve a question too,

    Now i’am having a Blog index page with latest posts only http://www.globalintegra.com/blog, i just want to include videos and photos in this blog index with setting minimum height to the post for videos and photos, after that i want continue reading as it placed now

  26. I have this in a page kind of like a small gallery but its limited due to:

    Settings >> Reading >> Blog pages show at most

    Is there a way around this to grab all images no matter what the limit is from settings?

  27. @Ritesh Sanap
    try the following code it should solve the problem .


    function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    if(preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches)){
    $first_img = $matches [1] [0];
    return $first_img;
    }
    else {
    $first_img = "/images/default.jpg";
    return $first_img;
    }
    }

  28. As a few others asked, I only recently discovered this doesn’t apply to pages. Any chances there’s a way to make it apply to them as well? Much thanks to anyone who figures out how!

  29. Hi.

    I love this and I’m implementing it in a theme I’m working on right now.
    There is however one thing I’m missing. Is there a way to make the image clickable? So when I click the image. It will for example open the original image in lightbox? šŸ™‚

  30. I use featured images on my website all the time. What I want to do is make it so the featured image doesn’t show up on the home page but only in the actual post. Any way to do this?

  31. Very useful, thanks a lot!

  32. Cool man i was looking for this. Thanks

  33. Hi there,

    Thanks in advance. I did not view image. Only i view the image link. Not image. Any idea?

  34. Hi
    So, I copied the larger block to functions.php.
    Then where do I call it?, i.e. where do I put this line of code?

    Thanks for any help provided.
    Sorry if it is a dumb question šŸ™‚

  35. Great!
    Is there possibility to modify the first part of code to automatically enter and save the image in the wordpress media and then add it as Featured Image?
    Thx

  36. hey; where to put the second code;

    please anyone reply to me

  37. Nice, any idea for get the image when the post has only a gallery shortcode ([gallery link="file" orderby="rand" rows="3"]) in his content?

  38. Exactly what I was looking for …
    Thank you

  39. hi,

    how to put image path in first_img.. i using my path not working.. any php code include before the image path.

  40. How can I choose the thumbnail. for example I would like to get in the thumb the top of the pictures instead of the middle of it.

  41. I was hoping this would fix a problem I have but it doesn’t. Can anyone tell me what I could do to choose first image attached? Basically I have a site where there is a upload form for each post. Registered users can submit photos which ARE attached to the post. If I log in and look at the post it shows them all as ATTACHED.

    When I use the above code it goes straight to the default backup IMG. Any suggestions for my scenario?

  42. Thanks for this tutorial! I’m actually going to be adapting it a bit to work on a non-WP site and to output thumbnails instead of the full image, but this is awesome. My first thought was to just use an explode function instead of preg, but I’m assuming the preg should be more efficient since it’s only storing the images it finds, rather than the entire group of text?

  43. Please help! I tried inserting this and have managed to break my site
    :-< got a fatal error and want to cry :'(

  44. Thanks for this tutorial! Iā€™m actually going to be adapting it a bit to work on a non-WP site and to output thumbnails instead of the full image, but this is awesome.

  45. Thanks for the function, it works pretty good.
    Here is a code sample from my modified home page – It restricts the number of posts as well as orderby date.
    8, 'order'=> 'DESC', 'orderby' => 'post_date' );
    $postslist = get_posts( $args );
    foreach ($postslist as $post) : setup_postdata($post); ?>

    <img class="recent-post-image" src=""/><a href=""> -

    I also use Jquery to hide the default image.

    Good luck!

  46. Thanks.
    Can someone answer Michael’s question?

  47. Very usefull…but, the image is the thumbnail one ex: image-188×145.jpg, is it possible to get the full size image or to automaticly change the name with no -188×145

    Exemple:

    If name is -188×145.jpg than .jpg

    Thanks

  48. Excellent bit of code. A real help. Thank you!

  49. Trying to modify a theme which used to display image only if it has featured image and not first image. This function seems interesting to me. Will try it at local host and once it truly works, I’ll upload the code to live site.
    I’ll comeback later with success story or a question when it fail.

    ‘Arick

  50. Chris Bohman

    I found that this works wonderfully when used inside the loop, however when I tried to catch_that_image() on a specific post (e.g. catch_that_image($some_post_id)) I was out of luck. It’s obvious that the code doesn’t support such functionality so I thought I’d post my revision.

    function catch_that_image_oustide_loop($some_id) {
    $fetch_content = get_post($some_id);
    $content_to_search_through = $fetch_content->post_content;
    $first_img = ”;
    ob_start();
    ob_end_clean();
    $output = preg_match_all(‘//i’, $content_to_search_through, $matches);
    $first_img = $matches[1][0];

    if(empty($first_img)) {
    $first_img = “”;
    }
    return $first_img;
    }// Catch that image outside the loop

  51. Chris Bohman

    Danny and/or Michael,
    this function returns a url or relative directory (e.g. /wp-content/uploads/13/01/09/example-img.png) so if you were to get more than one image, it would change how you use the output.

    if you use this as intended

    two images in that src will cause problems so we don’t want to have the function output $matches[1][0] and $matches[1][1] and $matches[1][2]. Nor do we want to lop through that array getting all of the results.

    We can pass a variable into the function denoting which image to get (see below)

    function catch_that_image($which_image = 0) {
    global $post, $posts;
    $first_img = ”;
    ob_start();
    ob_end_clean();
    $output = preg_match_all(‘//i’, $post->post_content, $matches);
    $first_img = $matches [1] [$which_image];

    if(empty($first_img)){ //Defines a default image
    $first_img = “/images/default.jpg”;
    }
    return $first_img;
    }

    Then when using the function simply add the image number into the function, and then you can get as many images as you want, this way.

    and so on.. and so on.. You get the idea. I would suggest using this method however I have not tested it myself

    if you need to catch all the images regardless of how many there are, try:

    function catch_all_those_images() {
    global $post, $posts;
    $first_img = ”;
    ob_start();
    ob_end_clean();
    $output = preg_match_all(‘//i’, $post->post_content, $matches);

    return $matches;
    }

    foreach($matches[1] as $image_src){
    echo “”
    }

    And when you need to use the function, don’t put it inside of the src attribute just “catch_all_those_images()”

    Again, not tested.

  52. Chris Bohman

    I tested the solution I gave for Danny and/or Michael, worked like a charm. The only change I would make is to offset the image number so that you can put 1 in for the first image instead of zero. Like so..


    function catch_that_image($which_image = 1) {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('//i', $post->post_content, $matches);
    $first_img = $matches[1][$which_image-1];
    if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
    }
    return $first_img;
    }

  53. Chris Bohman

    Edit Post maybe?
    I killed the preg_match_all function somehow.


    function catch_that_image($which_image = 1) {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('//i', $post->post_content, $matches);
    $first_img = $matches[1][$which_image-1];
    if(empty($first_img)){ //Defines a default image
    $first_img = "/images/default.jpg";
    }
    return $first_img;
    }

  54. gautam kumar

    function catch_that_image() {
    global $post, $posts;
    $first_img = ”;
    ob_start();
    ob_end_clean();
    $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;
    }

    i use this its work properly …….but how can manage image size ……plz help me

  55. The function returns the last image found. To get the first, use /U at the end of the regular expression instead of /i. Also, the url will be in $matches[1] not in $matches[1][0]. This way it will stop at the first result found.

  56. Thanks for the function, It workes fine.

  57. Thank you, this is great!

  58. Does anyone know how to re-write this for phpbb?

  59. Hi, can anyoe tell me how to get the second image from my post, i have searched about it alot but didn’t find an appropriate solution
    Thanks

  60. There’s a problem with the default image path with pretty permalinks. If you’re logged-in and deliberately view a post that has no image, that’s fine in the loop, it’ll show the default image, but if you see it in a category listing, it will return a 404 since the path is like ~/category/images/default.jpg.

    How to overcome this … ?

  61. The default image path won’t work for category or search listings with pretty permalinks turned on!

  62. hello,

    is it possible to catch images between [img][/img] too?
    i need to regex for both html and bbcode tag

  63. Hey, it’s possible to grab the medium size image?

    This function only gets the original image, I would like to get the medium one.

    Cheers,

    Telmo

  64. hi guys , i used this code in my theme but its just showing the url of the image what should id do?

  65. me too.. For me it returns the URL rather than the image.
    Any ideas?

  66. If you’re getting the URL rather than the image it’s because you didn’t put the HTML image tag inside your template.

    Go to your template where you want to output the image and add something like:

    <a href="”><img class="alignleft size-full" src="” alt=””>

    The issue I’m having is that if the post already has an image at the top, it’s doubling up both of the images since it’s the first image already. It ends up showing both at the same time and looks like crap.

  67. Could you please explain how could I modify the piece of code so that I can choose different images for different categories in case if there is no first image present in the post?

  68. HI there,

    I am not a programmer, just wondering how to actually change this code so that it will display the post images from a certain category and also provide a pagination below the result.

    THank you so much!!!!

Leave a Comment

Your email address will not be published. Required fields are marked *