Wordpress Hack : Get the first Image from the post and display it

by Deineshd on December 31, 2009

This is the first post about the wordpress hack published on Bloganol about getting the first image from the post and displaying it.This is really useful wordpress hack and also requested by many users.Thanks to Wprecipes for publishing code for such important hack.
thumb Wordpress Hack : Get the first Image from the post and display it

To implement this hack on your wordpress blog First of all copy the following block of code and paste it to your functions.php file.

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;
}

Now in second step Paste the following code where you would like to display the Image.This Tag simply call the function within the loop to display the first image from the post:

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

Consider to Subscribe to our RSS feed or Follow us at Twitter or Join our Facebook Fan Page.Enter your Email below to subscribe to our updates via Email.

Enter your email address:

Delivered by FeedBurner

Similar Posts

Powered by Thesis

Thesis Theme

An amazing WordPress Theme, nothing beats the versatility and SEO friendliness of the Thesis framework.

From beginners, to the most advanced WordPress developers, Thesis makes it easy for anyone to customize it.

{ 2 comments… read them below or add one }

daryl January 1, 2010 at 3:18 am

can this work on blogger?

Reply

Deineshd January 1, 2010 at 8:03 am

Since it is a wordpress hack so it doesn’t work on Blogger.There is different hack for blogger to help you.Visit here to learn

Reply

Leave a Comment

Previous post:

Next post: