Retreive First Image From WordPress Post
I have been looking around for this for ages. I have been using other post thumb plugins and just find them to bulky for what i wanted, too feature rich. I just wanted a basic grab the first image from a post and display it. Just add the below code to your functions.php file in your theme directory.
// Get URL of first image in a post
function get_first_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];
// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}To call it just put
<?php echo get_first_image() ?>
in your template file within the loop.
.via { WordPress Forums }




