CDN

CDN

What is Photon? this is a question I asked myself when I went looking for the name of the Jetpack app that does Image CDN (Content Delivery Network). Photon according to the WordPress.com documentation:

Photon is an image acceleration and modification service for Jetpack-connected WordPress sites. Converted images are cached automatically and served from the WordPress.com CDN. Images can be cropped, resized, and filtered by using a simple API controlled by GET query arguments. When Photon is enabled in Jetpack, images are updated on the fly. We want to create the best image manipulation and acceleration service in the world for WordPress users. Photon is only allowed to be used by sites hosted on WordPress.com, or on Jetpack-connected WordPress sites. If you move to another platform, or disconnect Jetpack from your site, please also switch to another magic image service. We can’t promise it will continue to work if you stop using WordPress or Jetpack. Abuse of Jetpack or violation of the WordPress.com Terms of Service could result in suspension of your site from WordPress.com-connected services.

I can’t remember where I found the following code:

add_filter( 'the_content', 'wpse39167_replace_image',9999 );
function wpse39167_replace_image( $content )
{
	$content = preg_replace_callback( "@<img.+?src=[\"'](.+?)[\"'].+?>@", 'wpse39167_maybe_replace_image', $content );
	return $content;
}

function wpse39167_maybe_replace_image($matches)
{
    if(!$matches[1])
		return $matches[0];

    $counter = wpse39167_static_counter( $matches[1] );
    $wp = 'http://i'.$counter.'.wp.com/';
	$url = str_replace(array('http://','//'),$wp,$matches[1]);
	return str_replace($matches[1],$url,$matches[0]);
}

function wpse39167_static_counter( $url )
{
        srand( crc32( basename( $url ) ) );
        $static_counter = rand( 0, 2 );
        srand(); // this resets everything that relies on this, like array_rand() and shuffle()
        return $static_counter;
}

but adding it to my themes functions.php causes (some) images to come from the WordPress.com CDN. Images that don’t get cached and CDN are ones in my theme, in the polaroid esc image galleys, or images that are linked to directly.

I am going to test the above code out for a week here, and if it looks like a keeper, I will run it out to the Biscuit Magazine site.