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.
Thank you for this really helpful piece of code
That’s exactly what I’m searching for.
What would the code look like if I wanted to do something else if it doesn’t find an image in the post?