WP-Mix

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:

// support featured images
if (!current_theme_supports('post-thumbnails')) {
	add_theme_support('post-thumbnails');
	// set_post_thumbnail_size(130, 100, true); // width, height, hard crop
}

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:

// display featured image
function display_featured_image($content) {
	global $post;
	
	$img_path = '/path/to/fallback/image.jpg'; // fallback image
	
	if (is_single()) {
		if (has_post_thumbnail()) {
			the_post_thumbnail();
		} else {
			$attachments = get_posts(array(
				'post_type' => 'attachment', 
				'post_mime_type'=>'image', 
				'posts_per_page' => 0, 
				'post_parent' => $post->ID, 
				'order'=>'ASC'
			));
			if ($attachments) {
				foreach ($attachments as $attachment) {
					set_post_thumbnail($post->ID, $attachment->ID);
					break;
				}
				the_post_thumbnail();
			} else {
				$content = '<img src="' . $img_path . '" alt="">' . $content;
			}
		}
	}
	return $content;
}
add_filter('the_content', 'display_featured_image');

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

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress