How to Implement a Robust, Usable Image Thumbnail Solution in WordPress

There’s a trend in modern WordPress theme design of incorporating image thumbnails into the template.   This is especially obvious when looking at Magazine style templates, or templates designed for image-heavy sites.   take a look at the work over at Woo Themes, one of the most popular theme sellers, and you’ll see that all of their themes support thumbnails in one way or another.   So how do you go about adding an image thumbnail to a WordPress theme?

Background

I’ve recently soft-launched a photoblog, which can be found at http://simontphotos.com.   I took a look around and none of the available WordPress themes grabbed me.   They were either too clunky, or cluttered, or distracting.   Or, at the other end, they were too simple and didn’t have the style I was after.   So I had to create my own.   I thought about it, and realised that to make the blog usable, I’d have to use thumbnails to draw people into the posts, getting them to view more of my photos.   I had another requirement, when viewing the main post, I wanted to display the image front and centre, outside of the main body of text.   This meant that for every post I needed two different sizes of of each image.   This isn’t something I wanted to do manually, so I needed a system of automatically resizing them.

Before tackling these requirements, it’s important to understand that there isn’t specific WordPress functionality for this task.   While it accepts and re-sizes images, it doesn’t make any images available to use in templates specifically.   They just appear in line with the rest of the post, which makes it difficult to style these images on their own.   It’s nigh on impossible to implement a thumbnail using in line images, and if you could to it, it would be a hack that would be difficult to use.   WordPress will also re-size images to sizes it feels are appropriate, which takes away an element of control.

Custom Fields to the Rescue

Fortunately, WordPress provides a feature called “Custom Fields“.   This allows you to assign a value to a post and give that value a name.   So when you’re designing your theme, you specifically return the value of that custom field.   For the purpose of this post, we’ll be creating a custom field called “image”.   This will hold the URL of the image you want to associate with your post as a thumbnail.

The custom field feature can be found towards the bottom of the post creation page in WordPress.   The “key” is the name of the value, where “value” is the value itself.

Putting it to Work – The Post

So now we have a plan, let’s put it into practice.   Adding a thumbnail to a post is a two step process.   Firstly, you have to upload the image, secondly, you have to associate that image with the post.   Of course, if you are using an image that’s hosted elsewhere, you can skip the first step.

We’re going to use the standard WordPress image management functionality to upload our images.   You should be familiar with this (click the “Add an image” button, choose an image to upload).   After uploading an image, you should be presented with a screen similar to the one to the right.   It’s the “Link URL” value we’re interested in.   This is the location on your site where this image lives.   This is a configurable location, but will usually   be in folders organised by date.   You want to copy this URL.   When you’ve done this, make sure to Save the changes, and not “Insert into Post”.

The next step is to associate that URL with the post.   This is done by creating a new custom field with the key “image” (Note:   I’ve used image, you can use anything so long as you remember it for the rest of this article).   The image below shows how to add a custom field.

Note that in the image above a drop down menu is present that contains the option “image”.   This drop down contains a list of all the custom field keys you have previously used.   If you’ve not used any, it won’t appear and you’ll have to manually type image into the Key field.   Then, simply paste the URL you copied earlier into the Value field, and click “Add Custom Field”.   That’s it, the image URL is now associated with your post.   So let’s look at getting that into your theme.

Putting it to Work – The Theme

If you’re reading this post, I’m going to make an assumption about you – you are at least passingly familiar with WordPress Theme Development and PHP.   You may be able to work your way through this post if you’re not, but any problems you come across may be insurmountable.

Retrieving a custom field in a WordPress theme is remarkable easy.   There’s a function called get_post_meta which takes three arguments – the Post ID, the Key (or name) of the value, and whether you want it to only return one value or not.   When invoked it returns (note that it returns the value as opposed to printing it) the value held against that post with that key.   Use it like this:

get_post_meta($post->ID, "image", true);

That returns the URL of the image you have associated with the post.   All you have to do is echo out the URL as the SRC attribute of an IMG tag, like so:

<img src="<?php echo(get_post_meta($post->ID, "image", true)); ?>" />

And that will display the image associated with your post in your theme.   This really is touching the surface of what’s capable and will display the image in the same size as it was uploaded as.   You’ll also want to wrap a link around the image and make sure there’s an alt attribute in there.   I would image you’d also want to add a class or two to help with styling.

Taking it a Step Further

As I mentioned at the start of this post, I want to do something a bit different.   I need the image in two different sizes.   I don’t want to have to re-size the images myself and then upload multiple copies, that’s far too time consuming.   So what we need is a way to automatically re size the image depending on what we want to use it for.   Step Up phpThumb.   phpThumb is an open source PHP script that will automatically re-size images for you.   One of the strengths of phpThumb is that is caches images, which means that it only re-sizes them once, saves the re-sized version on your server, and then serves the saved version.   This speeds up your page loads and reduces the strain on your server.   There are also a load of options, but we’ll look at those later.

To use phpThumb, you need to store the script in your themes folder (it doesn’t have to be, but it really is best if you plan on making the theme portable).   Then, instead of calling the image directly you call the phpThumb script and give it the URL of the image you want to re-size and the size you want to output to be.   So, instead of this:

<img src="http://www.yoursite.com/image.jpg" />

You will have this:

<img src="http://www.yoursite.com/phpthumb.php?src=image.jpg&w=100&h=75" />

The second URL will result in an image that’s been scaled to 100 pixels wide by 75 pixels high whereas the first one will just display the image in its native size.   The first time this URL is called, phpThumb will re-size the image and save it on your server.   Subsequent calls will simply serve the previously saved image.   So, to incorporate that into our theme, we would do something like this:

<img src="<?php echo TEMPLATEPATH; ?>/phpthumb.php?src=
<?php echo (get_post_meta($post->ID, "image", true)); ?>
&w=100&h=75" />

That code will result in the image you added to your post being re-sized to 100 by 75 pixels and displayed.   Easy, huh?   Warning: The script above makes some assumptions about the location of the phpThumb script, please change it as necessary to suit your needs.

Getting Super-Advanced

I bet you’re pretty happy with the results.   But there’s so much more you can do with phpThumb.   Below is the function I use to generate the phpThumb URL.

<?php
function thumbnail_url_builder($url,$width,$height,$zc,$copyright) {
       /*  
              This custom function uses the PHP Thumb script to build a URL for a scaled image
              There are additional options like copyright, size and whether to Zoom Crop
              To see more information on PHP Thumb - http://phpthumb.sourceforge.net/
       */
       $tn_url = get_bloginfo('template_url').'/phpThumb/phpThumb.php?'; //   Base PHPThumb URL
       $tn_url .= 'src='.$url;   // Add original image URL
       $tn_url .= '&amp;w='.$width; //   Add Width
       $tn_url .= '&amp;h='.$height; //   Add Height
       $tn_url .= '&amp;q=90'; //   Add Quality, default to 90
       //   Zoom Crop or not?
       if ($zc == 'true') {
              $tn_url .= '&amp;zc=1'; //   Zoom Crop is true (On)
       } else {
              $tn_url .= '&amp;zc=0'; //   Zoom Crop is false (off)
       }
       //   Add copyright?
       if ($copyright == 'true') {
              $tn_url .= '&amp;fltr[]=wmt|Copyright 2008|2|BR|FFFFFF||50'; //   Add copyright
       }
       $tn_url .= '&amp;f=jpg'; //   Set Output Format
       return $tn_url;
}
?>

This function provides me with several options.   I can control the size, quality and format of the image as well as optionally adding a copyright watermark and deciding whether I want to use Zoom Crop (Zoom Crop will display part of the image, in the requested size, retaining its aspect ratio.   Turning it off will display the full image in the requested size but will change the aspect ratio) or not.   I’m not going to go through the options in detail, they are all covered in detail on the phpThumb site.   But as you can see, the tool is pretty versatile and works well when trying to create thumbnails.   My function is called like so:

<?php
              if (get_post_meta($post->ID, "image", true)) {
                     //   There is an image
                     //   Get the url for a scaled version of the image
                     $tn_url =
thumbnail_url_builder(get_post_meta($post->ID, "image", true),'289','100','true','false');
                     //   File does exist, go ahead and print it
                     ?>
                     <p><a href="<?php the_permalink(); ?>">
<img src="<?php echo $tn_url ?>"
alt="<?php the_title(); ?>" /></a></p>
              <?php
              } // end if image
?>

If you try this technique, be sure to let us know your results and / or any problems you come across.