Automatic Post Thumbnails Without Plugins

Recently I had to make a WordPress theme for someone who is very uncomfortable with the technical process of downloading pictures and uploading them, so asking this person to resize or crop photos to make thumbnails was out of the question. Regardless, she needs to have a unique picture on each post of her new site – so my challenge was how to make that as easy as possible.

Now certainly, I could have used one of the php bits to create thumbnails on the fly like TimThumb – but I really dislike using plugins for things I can do without them. She also gets totally confused using custom fields, so that’s out as well.

What I needed to do:
1. Determine a standard size for thumbnails and post images that would work well for her theme.
2. Create a post thumbnail using the first image attached to a post.
3. Display the post thumbnails on the blog main page listing of recent posts.
4. Create a standard image that would be displayed if she forgot to add any images to a post.

Since I’m a big fan of reusing code, I decided I wanted to use the built in sizing options of WordPress to get this done. I remembered recently reading an article with a chunk of code, so I found it again and reused that. The code process can be found on Web Developer Plus.

Setting The Image Sizes

Go to your WordPress backend and then Settings -> Media and configure the sizes that work well for your theme.

The thumbnail size is the most important. I set this one to 150px by 150px and selected the option to crop the thumbnails to that size. The reason I selected the crop is in the likely case the photo she’s using isn’t a perfect square, the image won’t look out of proportion when it’s sized down to 150×150.

Creating a Thumbnail From The First Image

This is where we get the code bit from Web Developer Plus and with a couple of minor changes end up with this:

<?php
// Get images attached to the post
$img = null;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'order' => 'ASC',
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$img = wp_get_attachment_thumb_url( $attachment->ID );
break;
} ?>
<!-- Display the image in here -->
<?php }
?>

The code, at this point, doesn’t do much but it will in the next steps. I do want to stop and explain the terminology a bit. You’ll notice the use of the word ‘attachment’ in the code above. That’s how WordPress identifies the image associated with the post. Think of sending an email and attaching photos to it. The code finds the images attached to the post and selects the first one. It puts the information about that image in the $img variable we’ll use later.

It is important to note that this only works for attached photos because that is what WordPress it set up to handle. That means that if you host your photos elsewhere and just link to them – it’s not going to work. You have to actually upload them into WordPress using the media uploader.

Deciding Where To Put The Thumbnail Code

Since I want the thumbnails to show up on the main page of the site in the list of recent posts down the content section, I need to edit the index.php that displays the content. Your site may use the_content() but in this example the site is using the_excerpt(). It doesn’t really matter, so long as this stuff goes inside the loop but before the spot you want to show your photo.

<div class="thecontent">
<?php the_excerpt(); ?>
<span><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>" class="readon">Read the rest of '<?php the_title(); ?>'</a></span>
</div> <!-- end thecontent -->

I’m going to add the bit of code right above the call to the_excerpt() because that’s easiest at this point.

<div class="thecontent">
<!-- get the thumbnail -->

<?php
// Get images attached to the post
$img = null;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'order' => 'ASC',
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$img = wp_get_attachment_thumb_url( $attachment->ID );
break;
} ?>
<!-- Display the image in here -->
<?php }
?>

<!-- end get the thumbnail -->
<?php the_excerpt(); ?>

Display the Thumbnails on the Main Page

Now the code is actually in the area it should be, but it’s still not going to show anything until we put something in place of the ‘<!– Display the image in here –>’ placeholder. What the code HAS done is created the $img variable we can call. So let’s get that working by putting in some code that will call the image.

<div class="thecontent">
<!-- get the thumbnail -->
<?php
//Get images attached to the post
$img = null;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'order' => 'ASC',
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$img = wp_get_attachment_thumb_url( $attachment->ID );
break;
} ?>

<!-- ***** THE ACTUAL IMAGE ***** -->
<span class="the-thumbnail">
  <a href="<?php the_permalink(); ?>">
    <img src="<?php echo $img; ?>" />
  </a>
</span>
<!-- ***** END THE ACTUAL IMAGE ***** -->

<?php }
?>
<!-- end get the thumbnail -->
<?php the_excerpt(); ?>

What the above code has done is take the placeholder and replace it with a call to the image.

Then since this is for a front page thumbnail, we want people to go to the main article so we create a link around the image that points to the article.

Finally, for CSS styling I wrapped it in a span called the-thumbnail (you can wrap it in something other than a span, name the class anything you like, and style it any which way you can think of).

But What If… There’s No Image?

But wait… what if my client forgets to add an image to a post? That one article will look strange on the main page without an image when most of the others have one.

I want to create a fail-safe for dealing with an instance where she might forget to put in a photo for the post. What to do first is create some kind of dummy image (maybe just a large square with the site logo / branding or whatever you want). Upload that image somewhere.

<!-- ***** THE ACTUAL IMAGE ***** -->
 
<!-- # if post has an image # -->
<span class="the-thumbnail">
  <a href="<?php the_permalink(); ?>">
    <img src="<?php echo $img; ?>" />
  </a>
</span>
<!-- # END if post has an image # -->

<!-- # if post doesn't have an image -->
<?php } else { ?>
<span class="the-thumbnail">
<a href="<?php the_permalink(); ?>">
<img src="http://thedomain.com/fallback-thumb.jpg" />
</a>
</span>
<!-- # END if post doesn't have an image -->

<!-- ***** END THE ACTUAL IMAGE ***** -->

The most important line in that new section is <?php } else { ?> — that tells it to do something if there is no photo.

You’ll see that you can just as easily change the url of the image to be any image location you upload the fall-back image to.

Putting It All Together

So here’s what we came up with after that. I’ll highlight the sections of my template code so you can see where I put it inside the template. Remember, your index page may not use the_excerpt() – it may use the_content(). That’s perfectly ok so long as:

1. You put the code that generates the thumbnail somewhere inside the loop – the loop beginning looks like this: <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
2. You put the image display code where you want it to be.

So here’s the final code I used on my clients site:

<div class="thecontent">

<!-- get the thumbnail -->
<?php
//Get images attached to the post
$img = null;
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'numberposts' => -1,
'order' => 'ASC',
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
$img = wp_get_attachment_thumb_url( $attachment->ID );
break;
} ?>
<!-- ***** THE ACTUAL IMAGE ***** -->
 
<!-- # if post has an image # -->
<span class="the-thumbnail">
  <a href="<?php the_permalink(); ?>">
    <img src="<?php echo $img; ?>" />
  </a>
</span>
<!-- # END if post has an image # -->
 
<!-- # if post doesn't have an image -->
<?php } else { ?>
<span class="the-thumbnail">
<a href="<?php the_permalink(); ?>">
<img src="http://thedomain.com/fallback-thumb.jpg" />
</a>
</span>
<!-- # END if post doesn't have an image -->
 
<!-- ***** END THE ACTUAL IMAGE ***** -->
<?php }
?>
<!-- end get the thumbnail -->

<?php the_excerpt(); ?>

Oh, and remember — if you don’t like the size your thumbnails are coming out as — change it in Settings -> Media.

I hope you found that useful 🙂

~Nicole

11 Replies to “Automatic Post Thumbnails Without Plugins”

  1. Nicole,

    This is an excellent solution, however I have question. We are in the midst of installing a new theme. In order to accomplish a similar outcome, it requires the author of the post to copy the url location of the post photo and paste that address into a custom field called “thumb.” I fear the same issue with our many contributors, that they will most likely forget to complete the process and copy the url of their post photo to this custom field.

    Any thoughts on how to accomplish the same thing (automatic “thumb” thumbnail) and a fallback if no photo.

    Thanks much,

    Kevin Preblud
    Publisher and Founder

  2. @Kevin

    Good question! I suppose the answer would depend on if your preference is ripping out the existing functionality and replacing it with the one in this post, or using the existing method of the custom field while providing a check to see if it has a value.

    I can only guess what the code would look like in your theme, as there are different ways to accomplish the code from the custom field.

    Let’s pretend your custom field name in the post page is ‘thumbnail’ then you could have any of these types of solutions in your theme currently.

    You might have one that absolutely requires a value in that field. No forgetting allowed.
    <img src="<?php get_post_meta($post->ID, "thumbnail", true); ?>" />

    Or you could have something that checks to see if you have a value in the thumbnail custom field before it tries to use it. That might work like this:

    <?php
    $thethumb = get_post_custom_values("thumbnail");
    if (isset($thethumb[0])) { ?>
    <!-- start showing the thumbnail -->
    <img src="<?php echo $thethumb[0]; ?>" />
    <!-- done showing the thumbnail -->
    <?php } ?>

    But what you would really need is something like this:

    <?php
    $thethumb = get_post_custom_values("thumbnail");
    if (isset($thethumb[0])) { ?>
    <!-- start showing the thumbnail -->
    <img src="<?php echo $thethumb[0]; ?>" />
    <!-- done showing the thumbnail -->
    <?php } else { ?>
    <!-- no thumbnail - start showing the default -->
    <img src="http://somesite.com/default.jpg" />
    <!-- done showing the default -->
    <?php } ?>

    On the other hand, you could find the piece of the code that calls the thumbnail, remove that code and replace it with the thumbnail solution on this post.

    If you want to keep the custom field method, and if that code bit I just posted doesn’t look like what you have in your theme… then I’d need to see what you do have in your theme and how you want to handle the images.

    ~Nicole

  3. I usually adopt a theme and customize the hell out of it, but that one needs to take care of custom fields in each and every post takes away from the joy of writing something new. It is all the more boring if you need to edit others’ posts so that listing pages look good.

    This was exactly what I was looking for.

    Thanks!

  4. I am getting the same thumbnail for each post.
    Have been trying to isolate the problem for a few hours, I think it is because the code requests the first thumbnail out of the whole set of thumbnails in the query.

    I came to this conclusion when I selected the order to be DESC.
    With the original code, the first image from my earliest post shows for all, with DESC the last image of my last post.

  5. Hi, Just like to tell you that this piece of info is one quick to the point, no nonsense, workable and effective way as fast as possible. It worked for me and thank you for the effort. Keep up the good work.

  6. thanks ! I made it work. maybe you can teach me how to add formatting to it… Like align left or align right. text wrapped…

  7. hay sir

    sir can u tell me how to add “Auto Post Thumbnail” in wordpress

    sir just look like this web site “http://www.theme-junkie.com”

    Plz Sir Tell Me About This mothed

    my web site is http://www.Gloori.Com

    this is my free wp theme

    sir this is my free wp theme link

    http://fthemes.com/demonstration/?wptheme=TodaysNews

    and this is download link

    http://fthemes.com/download/?theme=todays-news

    me not understand how to install “Auto Post Thumbnail” in my wp theme

    plz sir tell me about this im waiting for ur reply
    byee

  8. thanks! ,, I got it work for YARPP.. YARPP with thumbnails.. see it working in my blog with some CSS tweaks.

    Adding image through wordpress built-in featured image is a lot of work. nahhh . i want it automatic..

    thanks again..

Comments are closed.