Jetpack’s Photon module is a free image CDN that doesn’t require any configuration; as soon you activate it, all the images in your posts and pages will be downloaded, optimized, cached, and served from WordPress.com’s CDN. Magic!
Photon is applied to all images on your site, including images that may hosted somewhere else; if you one day added an image to one of your posts without actually uploading it to your Media Library, that image will be served through Photon too.
However, sometimes you’d rather not serve external images through Photon. After all, these images may already be served via another CDN! Luckily, Jetpack includes a filter to allow you to control which images get served by Photon. In the example below, we’ll only use Photon for images belonging to our site, and make sure none of the images that are not hosted on our site get processed by Photon.
/**
* Only use Photon for images belonging to our site.
*
* @see https://wordpress.org/support/?p=8513006
*
* @param bool $skip Should Photon ignore that
image.
* @param string $image_url Image URL.
* @param array|string $args Array of Photon arguments.
* @param string|null $scheme Image scheme. Default to null.
*/
function jeherve_photon_only_allow_local( $skip, $image_url, $args, $scheme ) {
// Get the site URL, without any protocol.
$site_url = preg_replace( '~^(?:f|ht)tps?://~i', '', get_site_url() );
/**
* If the image URL is from our site,
* return default value (false, unless another function overwrites).
* Otherwise, do not use Photon with it.
*/
if ( strpos( $image_url, $site_url ) ) {
return $skip;
} else {
return true;
}
}
add_filter( 'jetpack_photon_skip_for_url', 'jeherve_photon_only_allow_local', 9, 4 );
That’s all it takes!