How To Provide Fallback Featured Images For Posts

How To Provide Fallback Featured Images For Posts

Using Featured images puts you, the WordPress site-owner, between that rock and a hard place.

You want to use featured images in your theme because they add so much visual punch and grab attention. But ensuring that every post has a featured image can lengthen the time to write a post considerably and can be an unhelpful deterrent.

In this article, I’ll show you how you can keep a theme’s integrity and ease that authoring pain by using fallback featured images.

"You’ll have Something to Fall Back on After the War ---- if you Buy Victory Bonds. Canada's 9th Victory Loan"; poster depicts an image of a man lying on a pile of money and lighting his pipe with a bill. A man’s military uniform is hanging to the right of him, covered in spider webs.
Fallback images won’t have you sitting on a pile of dollar bills but they will leave you content!

Most modern themes make extensive use of images. This is only natural as bandwidth increases and our concerns about the size of images decreases as well the knowledge that sites are increasingly being viewed on tablets which excel in displaying images.

Selecting and preparing images, though, can be incredibly time-consuming and can act as a significant hurdle to writing new posts. Updating your site to use an image-heavy theme can be similarly daunting if that means going back through all your content and adding featured images.

Fortunately, incorporating fallback images – images that are used when a post does not have a featured image – is relatively straight-forward.

This is solution is based on having category images. Each category in your site will have an image assigned; it will be this image that gets used as the featured image for any post in that category that does not have its own featured image. It uses an existing plugin and some custom code and can be used with any theme.

Step 1 – Install WPCustom Category Image Plugin

There at least 10 plugins in the WordPress Plugin Repository that provide for category images. Why so many, I’m not sure, they must all have their own take on how to implement the feature.

I’ve chosen to go with WPCustom Category Image Plugin as it’s relatively simple, has good clean code (we’ll be using one of it’s functions), is easy to use and is compatible with WordPress 3.6+.

Install and activate the plugin.

Screengrab showing the category edit screen with additional image functionality
Adding a fallback image for all posts in Cats category

Step 2 – Add Your Category Images

Once the plugin is activated, you’ll need to add images for each of your categories, including Uncategorized if it exists.

Go to Posts > Categories and for each category, edit it and associate an image by click on the Upload / Edit Image button and either selecting an existing image from the Media dialog or uploading a new image.

Step 3 – Add the Custom Code

Our custom code hooks into the get_post_metadata filter and returns the ID of the image associated with the category assigned to the post. If a post has multiple categories assigned then it takes the first category.

As luck would have it, this will also ensure that the has_thumbnail function will also return true. That’s important as many themes, TwentyThirteen amongst them, call this function before attempting to output the featured image meaning that we can’t just hook into the call to get the thumbnail.

Using this code also means that this solution will work with any theme.

{code}

function fallback_get_post_metadata( $spare , $object_id , $meta_key , $single ) {

// only interested if this is a call for a thumbnail id in the public interface
if ( is_admin() || $meta_key != ‘_thumbnail_id’ ) return;

// check for an existing thumbnail – note cannot use any function that will set up infinite loop!
$meta_cache = wp_cache_get( $object_id , ‘post_meta’ );

if ( !$meta_cache ) {
$meta_cache = update_meta_cache( ‘post’ , array( $object_id ) );
$meta_cache = $meta_cache[$object_id];
}
// if post has a thumbnail then return null to contine
if ( isset( $meta_cache[$meta_key] ) ) return $meta_cache[$meta_key];
// now we need to get the id for the category

// get the categories assigned to the post
$post_cats = get_the_category( $object_id );
// no categories, unlikely but can’t do anything
if ( count( $post_cats ) == 0 ) return null;
// we’ll just take the first
$term_id = $post_cats[0]->term_id;
// using function from plugin, get the id of the category image
$attach_id = WPCustomCategoryImage::get_attachment_id( $term_id );
// no category image, out of here
if ( !$attach_id ) return null;
// now store this in the post’s metadata using id _thumbnail_id
return $attach_id;

}

add_filter( ‘get_post_metadata’ , ‘fallback_get_post_metadata’ , 10 , 4 );

{/code}

So, what does the code do?

  1. It hooks into the get_post_metadata filter, which gets called in a multitude of places in WordPress so it first checks to ensure that this is a request for a thumbnail (featured image) ID in the public interface.
  2. If it is then it checks the mem_cache for the post to see if a thumbnail exists – this code is borrowed from the WordPress get_post_meta function. If it does then it returns the ID.
  3. If there is no existing thumbnail then it gets the first category for the post and then uses a function from the WPCustom Category Image plugin to get the categories image. This is returned as if it is the post’s featured image.

Where to put the code?

As per usual, you’ve got two choices. You could add it to your theme’s functions.php (or create a child theme) which would be perfectly valid considering this is theme-related.

Alternatively, you could add the standard WordPress plugin header to the code, zip it and load it as a plugin. The obvious advantage here is that it will be theme independent and, of course, can be switched off without having to edit your theme’s files.

There’s a download at the end of the article that has the code wrapped up as a plugin.

Or, Forget The Custom Code and Just Edit The Theme

Alternatively, you could forget the code and just edit your theme where it displays a post. For some themes, such as TwentyThirteen, this actually only means editing one file, content.php.

To add fallback images to TwentyThirteen, open content.php and replace

{code}

<?php if ( has_post_thumbnail() && ! post_password_required() ) : ?>
<div class=”entry-thumbnail”>
<?php the_post_thumbnail(); ?>
</div>
<?php endif; ?>

{/code}

With:

{code}

<?php if ( ! post_password_required() ) : ?>
<div class=”entry-thumbnail”>
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
} else {
// get the categories assigned to the post
$post_cats = get_the_category( $post->ID );
// no categories, unlikely but can’t do anything
if ( ( $post_cats ) ) {
// we’ll just take the first
$term_id = $post_cats[0]->term_id;

// get the category image (function provided by WPCustom Category Image function
category_image( array( ‘term_id’=>$term_id, ‘size’=>’post-thumbnail’ ) , true );
}
}
?>
</div>
<?php endif; ?>

{/code}

This adds a check (and display) of a category image if the post does not have its own featured image. Using the post-thumbnail size on the call to category_image ensures all the images stay the same size.

Whether you use the custom code or edit your theme, you can ensure that every post on your site will have a featured image without the need to go through and update all existing posts. It also means, of course, that if you move a post to another category then its fallback image will also change.

To really tighten up your featured images, you can combine the above with a plugin to require featured images before publishing.

How do you manage featured posts on your site? 

Download: Fallback Featured Images plugin

Image Credit: Department of National Defence, Ottawa