Posts tagged as:

timthumb

I spent a bunch of time trying to figure out how to retrieve the first image of a post. I found a bunch of articles with code samples and one plugin: Simple Image Grabber, WordPress Forum, Live Experience, WP Recipes, and Justin Tadlock. In nearly every set of comments, people were trying to figure out how to integrate the image retrieval code and Darren Hoyt’s TimThumb. Well, I’ve done it, and you can kype my code if you’d like.

This tutorial assumes that you’ve already got TimThumb installed on your site, that you know how to use it, and that it’s installed in your theme’s directory inside of the folder “scripts”.

The following code goes in your theme’s functions.php file. It is a modified version, taken from Smashing Magazine’s 10 Exceptional WordPress Hacks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Get the First Image
function catch_that_image() {
global $post, $posts;
$first_img = '';
$url = get_bloginfo('url');
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
 
$not_broken = @fopen("$first_img","r"); // checks if the image exists
if(empty($first_img) || !($not_broken)){ //Defines a default image
unset($first_img);
} else {
$first_img = str_replace($url, '', $first_img);
}
return $first_img;
}

Now, open up your template to the page where you want timthumb to display the first image in the post. Cut and past the following:

1
2
3
<?php $cti = catch_that_image(); if(isset($cti)){ ?>
<img src="<?php bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $cti; ?>&h=60&w=60&zc=1" alt="Link to <?php the_title(); ?>" class="thumbnail"/>
<?php } else {} ?>

{ 16 comments }

TimThumb

March 8, 2009

I just discovered a script that is being used on Mimbo Pro. Darren Hoyt has made it available on his blog for use by all designers. It’s an useful tool for grabbing images that are uploaded into a post and resizing them as thumbnails. Check it out. It’s called TimThumb and you can find it [...]

Read the full article →