Image Resizing With WordPress

During a recent project of mine, I needed a way to retrieve the first image from each WordPress post in a certain category, and then scale it to a certain size. I could’ve used a Custom Field for this purpose, and have the author paste the link to the image in a box; however I felt this would only confuse my client. Here’s a look at how it was done.

First thing we need to do, is limit our posts to a certain category. This is done using the query_posts() function:

<?php query_posts("cat=5&showposts=15");
while (have_posts()) : the_post(); ?>

This retrieves the first 15 posts in category 5. To retrieve the image, I used a custom SQL query (thanks to 185vfx).

<?php
$image = "";
$first_image = $wpdb->get_results(

"SELECT guid FROM $wpdb->posts WHERE post_parent = '$post->ID' "
."AND post_type = 'attachment' ORDER BY `post_date` ASC LIMIT 0,1"

);

if ($first_image) {
    $image = $first_image[0]->guid;
			  }
?>

What the above query does, is it retrieves the URL of the first attatchment for the current post and then stores it in a variable named $image for us to use.

The final requirement, is to scale the image to 200×100. We could easily do this in HTML or CSS, but the image would be squashed if it didn’t have the same 2:1 ratio – and even images which did would look very ‘jaggedy’.

The solution is to include a PHP script named TimThumb which will ‘intelligently’ resize the provided image to a size we specify in the URL:

<img src="<? bloginfo('template_directory'); ?>/timthumb.php
?src=<? echo $image ?>&w=200&h=100&zc=1" alt="<? the_title(); ?>" />

As you can see, we include the URL to the image as the src and set the width (w) and height (h) when including timthumb.php.

Finally, we close off the WordPress Loop:

<?php endwhile; ?>

I then integrated this into the jCarousel Lite plugin for jQuery to get the following effect:


14

Comments