3 Ways to add Thumbnails to WordPress Posts

A beautiful featured image standing aside to your posts may be a nice feature to have for your theme. Whether you want to give your website more color, a more professional or consistent look or just a way to visually showcase your work, you may just want to have your site powered with this. Here I will present you with my way of implementing this feature into a theme …

Gravity Forms Contact Form Plugin for WordPress A beautiful featured image standing aside to your posts may be a nice feature to have for your theme. Whether you want to give your website more color, a more professional or consistent look or just a way to visually showcase your work, you may just want to have your site powered with this. Here I will present you with my way of implementing this feature into a theme.

Since WordPress 2.9 there is built-in functionality for post thumbnails. Prior to that several tweaks were used to generate the thumbnails. In this article I will present how to implement the thumbnail core-functionality into the theme and also how to provide other alternatives for users that have versions older than 2.9 or have their site set up with old style to add thumbnails.

WordPress Featured Images

The new, built-in way to add thumbnail support to themes, available since version 2.9. Thumbnails were very popular way prior to this version, especially among magazine-styled themes, so a core functionality to add thumbnails was required to ease things up.

As any extended theme feature, support for it must be declared in the theme’s functions.php. Here’s how a standard implementation looks like:

if (function_exists('add_theme_support')) {
  add_theme_support('post-thumbnails');
  set_post_thumbnail_size(150,150);
}

First is checked if support for extended features exists, in order not to generate errors if users have versions prior to 2.9. Then, theme support for post thumbnails is declared and the default size of the thumbnails.

In this case, thumbnail support is added for both posts and pages. Let’s say you want to have this feature only for posts. In this case change the second line to this:

add_theme_support('post-thumbnails',array('post'));

The default thumbnails size is fixed and images are resized. If you want images to be cropped instead, change the third line to this:

set_post_thumbnail_size(150,150,true);

The third variable is the crop flag, which if set to true will crop your images instead of resizing them.

Well, not really. Until now I haven’t seen these parameters having any effect. If you want to declare a default thumbnails size and scaling method, I recommend you go to Settings › Media and set the thumbnail size and scaling method from there.

This only tells WordPress that post thumbnails are supported and adds an option to set the thumbnails in the editor. To display the thumbnail, the following code must be added in the template files in the location where you would like to display the thumbnail:

if (function_exists('has_post_thumbnail') && has_post_thumbnail()) the_post_thumbnail();

It is verified whether post thumbnails are supported and a thumbnail is declared and the last function displays it.

Several parameters can be given to the_post_thumbnail() function, I will stick only to one of them: size. The default  thumbnail size can be overridden in the following manner:

the_post_thumbnail(array(300,300));

The numbers correspond to width and height. In place of the array, predefined sizes can also be added, like ‘thumbnail’, ‘medium’ and ‘large’.

Set Featured ImageNow, if you go to the editor, you’ll see a nice new box called Featured Image, located on the right column, below the post tags, as shown in the image on the right. To select the image you would like to use as thumbnail, click on the “Set featured image” link. “The Add an Image dialog will show up where you can upload an image or select one from the Media Library. From here you can also select the size in which you would like to display the thumbnail; ignore the alignment as it does not apply in this case. To set the image as a thumbnail instead of simply inserting it into the post, click the “Use as featured image” link, shown in the image below. After updating the post the selected image will appear at the specified location in the post. You can remove or change this image later.Use As Featured Image

Now let’s say your users have a version older than 2.9, or have used a theme before that had a custom way to add thumbnails. Having the new thumbnail system may be nice, but they will also end up with a lot of broken images if the old thumbnail system is no longer supported. For backwards compatibility I still like to incorporate the old custom methods of adding thumbnails, along with the new built-in one. The most popular one is using the timthumb script:

Display a Thumbnail using the Timthumb Script

Timthumb is a script by Darren Hoyt that can scale images to any size. In this case, we will use it to refer to an image and display it as a post thumbnail.

As prior to version 2.9 there was no predefined way to add a post thumbnail, we’ll have to add it as custom information. The easiest way to do this is by adding a custom field.

Custom fields can be added in the editor, a bit under the text area like in the image below:Add Custom Field

In this case, we will use the name “Image” (you can give it any name) and for the value the image’s URL (relative URLs are also supported). By default only images from the current domain are displayed. To allow images from different domains, these have to be added as exceptions. This can be done by directly editing the timthumb script and adding a value to the variable $allowedSites. Just search for it, it’s somewhere at the beginning.

Now that we have out thumbnail declared, we must display it. For this add the following function:

<?php function my_post_thumbnail($width,$height) {
  $thumb = get_post_custom_values("Image");
  if (!empty($thumb)) : ?>
    <img src="<?php echo bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $thumb[0]; ?>&w=<?php echo $width; ?>&h=<?php echo $height; ?>&zc=1&q=100" alt="<?php the_title(); ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" border="0" />
  <?php endif; ?>
  return !empty($thumb);
}

Then call the function at the location where you want to display the thumbnail:

<?php my_post_thumbnail(300,300); ?>

Of course you can call directly the code in the function, I just find it more elegant this way. Now let’s see how we can display a thumbnail if the user hasn’t selected any. The returned value can be used to put the function in an if statement.

Display the first Image in Post as Thumbnail

Let’s say you would like an easy way to display a thumbnail, no edit, no bother. The best way to do this is to detect the first image in the post and display it as a thumbnail.

First, let’s create a function that detects and returns the first image in the post:

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);
  if(count($matches [1]))$first_img = $matches [1] [0];
  return $first_img;
}

Thanks to WpRecipes for the function.

Now let’s use the Timthumb script to insert the image in the post:

<?php function my_first_image($width,$height) {
  $thumb = catch_that_image();
  if ($thumb) : ?>
    <img src="<?php echo bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo $thumb[0]; ?>&w=<?php echo $width; ?>&h=<?php echo $height; ?>&zc=1&q=100" alt="<?php the_title(); ?>" width="<?php echo $width; ?>" height="<?php echo $height; ?>" border="0" />
  <?php endif; ?>
}

Call this function wherever you want to display the thumbnail. For some reason this doesn’t work if the first image in the post is a caption, I don’t know why.

And now how about a function that makes use of all 3 of them?

Wrap ’em all up

Here’s a function that verifies if native thumbnails are supported and displays it. If not, it will try to display the custom thumbnail and the first image in the post:

function display_thumbnail($width, $height) {
  if (function_exists('has_post_thumbnail') && has_post_thumbnail()) the_post_thumbnail(array($width,$height));
  elseif (!my_post_thumbnail($width,$height)) my_first_image($width,$height);
}

Don’t forget to declare the theme support and functions beforehead 😉

Now you should be able to add a nice thumbnail to the theme.

You can see this in action in my Cover WP Theme.

8 thoughts on “3 Ways to add Thumbnails to WordPress Posts

  1. This will work, but i would look for (in fact: am looking for) a one-time fix that adds the first image of all existing posts as the featured image of those posts, if undefined. With the functions shown here and knowledge of the WP tables that will provide a more solid solution without extending all themes. Do you know of such a fix? I could not find it

    1. Here’s an idea, untested:

      WorsPress stores the paths to the featured image in a hidden custom field called '_wp_attached_file' and assignns it as thumbnail through another hidden field called '_thumbnail_id'. Now if you could somehow associate these 2 with the function catch_that_image() you would get what you need or at least I think so.

  2. Thank you for this wonderful tutorial. I am not an expert (yet) in wordpress so this kind of tutorial really helps. =)

  3. I am using WordPress 3.1.3., is there a way to set a featured image from a URL? I access most of my graphics through URL’s.

    Thank you, and I love this site, it is becoming very successful.

    1. If you’re using timthumb you’ll have to add the domain to the array of trusted domains. Just look in the timthumb.php file, it’s somewhere at the beginning.

Leave a Reply

Your email address will not be published. Required fields are marked *