WordPress Code Snippets

A fresh mix of code snippets and tutorials

WordPress Set Featured Image with Fallback


In this tutorial, we’ll see how to enable theme support for Featured Images (aka Post Thumbnails), and also how to display them with fallback image support.

Step 1: Enable Featured Images

The first step is to enable featured images in your theme. There are numerous ways to do so, but the easiest imho is to add the following snippet to your theme’s functions.php file:

This code first checks to see if your theme already supports Featured Images. If it does not, then the required theme-support function is executed. The line that is commented out may be used to set any featured-image sizes in addition to the default sizes.

Step 2: Display Featured Images

Once your theme supports Featured Images, you can display them in your theme by adding the following code to the WP Loop:

Assuming that you’ve assigned/attached some Featured Images to your posts, this code checks to see if the current page is single, and if so displays whichever it finds first:

  1. Featured Image (via the_post_thumbnail())
  2. The first image attached to the post (via get_posts())
  3. The defined fallback image

That way every post on your site will display an image. There are many ways to customize such code, but the only thing that really needs attention is the image path, as specified in the variable $img_path. You want to make sure that the image exists and that the path is correct. Further customization is not required but always encouraged if desired.

Also, as written this code may be placed in the Loop of any relevant theme template file (e.g., index.php, single.php, singular.php, etc.). The if (is_single()) ensures that the image only will be displayed on single-post views. Thus, this code is placed in the theme’s single.php template, it would be safe to remove the if (is_single()) condition, as it always will return true in that case.

Learn more

WordPress Themes In Depth

Show Support

Like our new Facebook Page to show support!