Snippets: Fallback Post Thumbnail (Featured Image)

This snippet will allow you to set a fallback featured image anytime a featured image (post thumbnail) is requested on your WordPress site. The first function will add the post_thumbnail_id filter which doesn't exist by default in WP core and the second function adds the fallback.

// Add a filter for the post thumbnail ID since it doesn't exist in WP core
add_filter( 'get_post_metadata', function ( $value, $post_id, $meta_key, $single ) {
	
	// We want to pass the actual _thumbnail_id into the filter, so requires recursion
	static $is_recursing = false;
	
	// Only filter if we're not recursing and if it is a post thumbnail ID
	if ( ! $is_recursing && $meta_key === '_thumbnail_id' ) {
		$is_recursing = true; // prevent this conditional when get_post_thumbnail_id() is called
		$value = get_post_thumbnail_id( $post_id );
		$is_recursing = false;
		$value = apply_filters( 'post_thumbnail_id', $value, $post_id ); // yay!
		if ( ! $single ) {
			$value = array( $value );
		}
	}
	
	return $value;

}, 10, 4);

// Add fallback for post thumbnail
// So whenever a featured image is called if there isn't one for the current post it will return
// your fallback attachment
add_filter( 'post_thumbnail_id', function( $id ) {
	return $id ? $id : 5; // Set fallback to attachment with ID of 5
} );

Snippet Type: PHP

Posted Under: Other

All PHP snippets should be added via a child theme's functions.php file.