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

by Deineshd on December 31, 2009

Share


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.

{ 4 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

Mo April 2, 2010 at 3:56 am

I don’t understand the 2nd step. I am new to wordpress and dont have any experience with this stuff.

I pasted the first thing into the functions.php file. Where exactly do I paste the 2nd code? Into the actual post when I am typing it? Or in the functions.php file? And where do I paste it in there?

Reply

Deineshd April 2, 2010 at 1:09 pm

Since you are new at Wordpress so its really hard for me to make you clear about this Wordpress hack. This hack is hard for newbies so I suggest a wordpress plugin that help you do this work. The name of the plugin is Thumbnail for Excerts and this plugin does the same work easily that is done by this hack. Get then plugin from here http://wordpress.org/extend/plugins/thumbnail-for-excerpts/

Reply

Leave a Comment

Previous post:

Next post: