WordPress Post Thumbnails: Migrating from Custom Fields to the Featured Image API

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.

  • http://www.johan-ahlback.com Johan Ahlback

    Nice article! But not the way i would solve this problem. You should use a filter so you can use get_the_post_thumbnail and has_post_thumbnail. This should work:

    add_filter(‘post_thumbnail_html’, ‘if_thumbnail’ , 10, 5);
    function if_thumbnail($html, $post_id, $post_thumbnail_id, $size, $attr){
    global $post;
    $thumbnail = get_post_meta($post->ID, ‘thumbnail’, true);
    return $html;
    return ‘<img src=”‘. $thumbnail .'” />';

    • http://www.webmaster-source.com Matt

      That’s good. I didn’t know about that filter…

      • http://www.johan-ahlback.com Johan Ahlback

        I always look at the source code when i want to modify something. There’s always some filters or action hooks you didn’t know about. Btw, love your blog.

        • http://www.webmaster-source.com Matt

          Thanks. I love my blog, too. :)

          I end up digging through the source when I have to, but for simpler things I often end up reinventing the wheel instead…