RSSAll Entries Tagged With: "get first image"

Get the first image from a wordpress post and display it.

Hello friends , recently i came across some blogs that showed images under each post title on the index page . I needed to implement that in my blog , i found two methods to do it . Download a plugin named “Get The Image” and activate it or you can just copy paste the following code .

add the following code to functions.php

[php]
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;
}
[/php]

Once done, you can simply call the function within the loop to display the first image from the post.

[php]
echo catch_that_image() ;
[/php]

You are done !