Removing Site Icon from Jetpack’s OG tags fallback

In WordPress 4.3, a Site Icon feature was introduced, allowing users to set the icon used by browsers and smartphones when representing a given site. In Jetpack 3.9.2, the site icon was added as a potential fallback when choosing an image for social networks like Facebook.

As well-intentioned as the Jetpack update was, it suffers two problems. First, the source image for my site icon is small enough that it doesn’t meet the minimums required by the services that will use it; despite this, Jetpack still selects it. Second, I don’t want my site icon used as the fallback–it is very strange to see the same image associated with dozens of posts, especially when that image is also the avatar I use with many services.

Regarding the first issue, I’ve reported this to the Jetpack project: https://github.com/Automattic/jetpack/issues/3432.

To address the second complaint, I put together a small callback to replace my site icon with the blank image Jetpack would’ve otherwise chosen.

/**
 * Modify Jetpack's presentation of Facebook's Open Graph tags
 */
function eth_jetpack_og_tags( $tags ) {
	// Site icon is a bad fallback; see https://eth.pw/a0
	if ( is_string( $tags['og:image'] ) && has_site_icon() ) {
		$site_icon = get_option( 'site_icon' );

		if ( $site_icon ) {
			add_filter( 'jetpack_photon_skip_for_url', '__return_true' );

			$site_icon = wp_get_attachment_image_url( $site_icon, 'full' );
			$site_icon = pathinfo( $site_icon );
			$site_icon_regex = '#' . $site_icon['filename'] . '(\-([0-9]+)x([0-9]+))?\.' . $site_icon['extension'] . '#';

			if ( preg_match( $site_icon_regex, $tags['og:image'] ) ) {
				$tags['og:image'] = 'https://s0.wp.com/i/blank.jpg';
				unset( $tags['og:image:width'] );
				unset( $tags['og:image:height'] );
				unset( $tags['og:image:secure_url'] );
			}

			remove_filter( 'jetpack_photon_skip_for_url', '__return_true' );
		}
	}

	return $tags;
}
add_filter( 'jetpack_open_graph_tags', 'eth_jetpack_og_tags', 99 );

The above is also available at https://git.ethitter.com/snippets/14.

The process isn’t as straightforward as I’d have liked, due largely to the lack of filters in has_site_icon(). While I could’ve filtered the site_icon option via get_option()‘s filters, I generally avoid mucking around directly with options calls given the ease with which small mistakes can have catastrophic effects, and to avoid running a callback as frequently as get_option() can be triggered.

For scalability, it would be better if Jetpack offered a filter on the list of sources that will be checked when it searches for an image, allowing me to remove Site Icon from ever being considered. After all, it’s more likely the list of sources will grow: WordPress 4.5 will introduce a Site Logo feature, in addition to Site Icon.

Leave a Reply