Skip to content

Snippet: Add a Fallback Featured Image for Blog Posts

This is a simple way of adding a "fallback" image for your blog posts if you want a specific image to display when there isn't a featured image defined. Now, if you want there is a more complex way that will target ALL images on your site which you can find here.

/**
 * Trick WordPress into thinking the post has a thumbnail to bypass the "has_post_thumbnail" checks on the front-end.
 *
 * @link https://total.wpexplorer.com/docs/snippets/add-fallback-featured-image-blog-posts/
 */
add_filter( 'has_post_thumbnail', function( $has_thumbnail ) {
	if ( get_post_meta( get_the_ID(), 'wpex_secondary_thumbnail', true ) ) {
		$has_thumbnail = true;
	}
	return $has_thumbnail;
}, 10 );

/**
 * Add a fallback featured image ID for the blog entry and post thumbnails.
 *
 * @link https://total.wpexplorer.com/docs/snippets/add-fallback-featured-image-blog-posts/
 */
function myprefix_blog_thumbnail_fallback( $args ) {
	if ( ! get_post_thumbnail_id() ) {
		$args['attachment'] = 'YOUR_ATTACHMENT_ID'; // Upload the fallback image to wordpress and add it's post ID here
	}
	return $args;
}
add_filter( 'wpex_blog_entry_thumbnail_args', 'myprefix_blog_thumbnail_fallback' );
add_filter( 'wpex_blog_post_thumbnail_args', 'myprefix_blog_thumbnail_fallback' );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top