Get the First Image From Post

I had wanted to get the first image from a post since I started using wordpress. Problem was, I wasn’t smart enough to understand how to do it. Or how to even think about the ways to go around doing it. I was using the Post Thumb plugin but it wasn’t ever getting updated and it was getting a little bloated with features. I just wanted the ability to get the first image from a post. So finally I stumbled upon this thread, Where the solution was laid out right in front of me.

So, you need to edit or create the functions.php file in your theme directory. And add:

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];
// no image found display default image instead
if(empty($first_img)){
// $first_img = "/image/omg.png";
}
return $first_img;
}

and you call it in your template files in between the loop with:

<?php echo catch_that_image()?>

Next post I will show how to resize the post dynamically with TimThumb.

You can see a working example of this in use at: Marissa Textor and Obey Giant.

About Weston Deboer

I like to use wordpress for any and every website that I work on. No matter how big or how small the website is.
This entry was posted in Wordpress and tagged , , . Bookmark the permalink.

2 Responses to Get the First Image From Post

  1. Sidenote says:

    Thank you for this really helpful piece of code :) That’s exactly what I’m searching for.

  2. Brandon says:

    What would the code look like if I wanted to do something else if it doesn’t find an image in the post?

Leave a Reply

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

*

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