Justin Tadlock

How to define a default post thumbnail

I’ve seen a few tutorials floating around the WordPress-o-Sphere about setting a default post thumbnail for WordPress’ featured image functionality. Some involve tactics like saving a permanent default image (theme authors, please don’t do that).

A default thumbnail is generally not something that’s permanent, so you wouldn’t want to save it, leaving yourself a world of pain if you ever wanted to change it in the future. I’ll keep this simple and afford you that future flexibility. I’ll even show you two ways to do it.

Option #1: Using a hook

WordPress has an awesome filter hook called post_thumbnail_html that works great for this. If you’re using a child theme, this is a pretty good option. Just drop the following code into your theme’s functions.php. It will load an image called default-thumbnail.png from your theme’s /images folder.

add_filter( 'post_thumbnail_html', 'my_post_thumbnail_html' );

function my_post_thumbnail_html( $html ) {

    if ( empty( $html ) )
        $html = '<img src="' . trailingslashit( get_stylesheet_directory_uri() ) . 'images/default-thumbnail.png' . '" alt="" />';

    return $html;
}

Notes about this method:

  • This won’t work if your theme does a conditional check for the thumbnail such as with the has_post_thumbnail() function. Check with your theme author though; there might be alternate methods.
  • Use get_template_directory_uri() in the above code instead of get_stylesheet_directory_uri() if you’re working with a regular/parent theme.

Option #2: The tried and true method

There’s really no need to get fancy with hooks and such unless you’re trying to keep your theme’s templates clean (like when using a child theme). You can drop the following code right into your theme’s template.

<?php
    if ( has_post_thumbnail() )
        the_post_thumbnail();
    else
        echo '<img src="' . trailingslashit( get_stylesheet_directory_uri() ) . 'images/default-thumbnail.png' . '" alt="" />';
?>

There you have it: two simple ways to set default post thumbnails.