I had post thumbnails on this blog a long time before the feature became a part of the WordPress core. Some of you out there may have, too. The technique that was generally used before the friendly “Featured Image” box, and its associated theme API, was added to WordPress, we generally just pasting image URLs into custom fields and outputted them into an image tag in the theme. Basically, like I recommended in this old post from 2008.
When WordPress 2.9 was released, bringing with it an “official” way to handle thumbnails, I was a little bit annoyed. I had tons of posts where I had existing thumbnails that would have to be somehow updated, or else I would have to come up with some clever way to be backwards-compatible. So I just put it out of my mind and left things the way they were…until this year.
Redesigning gave me an excuse to modernize a lot of the stuff going on behind-the-scenes, and one of the things I improved was the handling of post thumbnails. The solution was easy: write a function to handle two methods of applying a thumbnail, and check both places for a thumbnail. The code looks something like this:
function my_smart_thumbnail($postid) { $custom_field = get_post_meta($postid, 'thumbnail', true); if ( has_post_thumbnail($postid) ) { $featured_img = get_the_post_thumbnail($postid, 'thumbnail'); echo '<div><a href="'.get_permalink($postid).'">'.$featured_img.'</a></div>'; } elseif ( $custom_field ) { echo '<div><a href="'.get_permalink($postid).'"><img src="'.$custom_field.'" /></a></div>'; } }
And then, in the Loop, where I want the image to appear:
<?php my_smart_thumbnail(get_the_ID()); ?>
With that, the old thumbnails keep working, but moving forward the new thumbnails take precedence.