How to add a default fallback image if no image can be found in a post

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 50% off your first year.

Explore plans

When you publish a new post on your site, Jetpack crawls it and looks for images that can be used when sharing that post on Facebook, on Twitter, or if that post appears in the Top Posts and Pages widget in your sidebar.

Jetpack starts by looking for a Featured Image. If you didn’t define any, we will look for slideshows and galleries, and then for any images that may be attached to the post. If we don’t find any image attached to that post, we’ll look for single images you may have inserted in the post. If you’ve inserted an image that is hosted on another site, we can use it too.

However, sometimes you may not have added any image to your post. In such cases, you can add this code snippet to your theme’s functions.php file, or in a functionality plugin. This way, your readers will see a default image when sharing that post on Facebook, for example:

function jeherve_custom_image( $media, $post_id, $args ) {
	if ( $media ) {
		return $media;
	} else {
		$permalink = get_permalink( $post_id );
		$url = apply_filters( 'jetpack_photon_url', 'YOUR_LOGO_IMG_URL' );
	
		return array( array(
			'type'	=> 'image',
			'from'	=> 'custom_fallback',
			'src'	=> esc_url( $url ),
			'href'	=> $permalink,
		) );
	}
}
add_filter( 'jetpack_images_get_images', 'jeherve_custom_image', 10, 3 );

It’s worth noting that the fallback image has to be larger than 200 x 200px, as per Facebook requirements. If your image is smaller, Facebook will ignore it.

Reference

This entry was posted in Code snippets, Tips & Tricks and tagged , , , , . Bookmark the permalink.

Jeremy Herve profile
Jeremy Herve

Jetpack Mechanic 🚀 at Automattic. WordPress, board games, TV Series, music.

Explore the benefits of Jetpack

Learn how Jetpack can help you protect, speed up, and grow your WordPress site. Get up to 50% off your first year.

Explore plans

Have a question?

Comments are closed for this article, but we're still here to help! Visit the support forum and we'll be happy to answer any questions.

View support forum
  • Enter your email address to follow this blog and receive news and updates from Jetpack!

    Join 112.8K other subscribers
  • Browse by Topic