Catch the First Image

You can catch the your posts first image and use them for thumbnails. Also you can use default images for this. With this function you can use any image (first image on your posts also) for thumbnail. Lets Begin…

Here is the code;

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)){ //Varsayılan küçük resim
$first_img = "wp-content/themes/tema adı/images/default.png";
}
return $first_img;
}

This is the output;

catch_that_image()

This is the usage;

Usage with the img tag;

<img src="<?php echo catch_that_image() ?>" alt=""/>

Usage on site;

<span class="custom_image">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Read: <?php the_title_attribute(); ?>"><img src="<?php echo catch_that_image() ?>" alt=""/> </a>
</span>

And CSS;

.custom_image img{float:left; padding:3px; margin:7px 10px 15px 0; border: 2px solid #e6e6e6; height:90px; width:90px}

That’s All!


Related posts:

If you enjoyed this post, make sure you subscribe to my RSS Feed
  1. Apr 12th, 2010 at 23:56 | #1

    Thank you so much.
    Can we grab images for Related Posts with this??

  2. Apr 13th, 2010 at 11:18 | #2

    @Kishore Mylavarapu
    Hi Kishore,
    You can use Related Posts With Thumbnails or you can combine this post with Related Posts Without any plugin

  3. John
    Jul 30th, 2010 at 19:36 | #3

    Where do you put the code? Everywhere I put it, it creates errors on the functions.php editor???? I even had to reload my pluggable.php file. OYEEEE

  4. John
    Jul 30th, 2010 at 19:50 | #4

    nevermind figured it out, need to tell users to put at the top of the functions.php file just under the <?php tag.

  5. Aug 1st, 2010 at 11:47 | #5

    John, sorry but i figured on all new wordpress themes have functions.php and code can insert to the end of file before "?>" The code worked for you? Have a nice day

  6. corp
    Oct 6th, 2010 at 23:46 | #6

    Thanks!

  7. Brian
    Nov 11th, 2011 at 18:38 | #7

    Is there a way to modify this code to include styles in the Functions.php, as opposed to on the page. I’m trying to create thumbnails and I want the function to say something like, “if there’s an image post it with a width of 100 px, but if there’s not an image default image = null.”

    I know it’s possible, but I can’t figure it out. Thanks!

    • Nov 12th, 2011 at 02:10 | #8

      Yes you can, I will write a post about this. Upgraded version of this code.

  8. Brian
    Nov 14th, 2011 at 23:39 | #9

    Thanks Serkan! You’re awesome! Will check it now.

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
 

Highslide for Wordpress Plugin