Over the weekend, I decided to add Jetpack Photon support to The-Nexus.tv. Photon is Automattic’s CDN magic image service. It’s neat and a feature I’ve been looking into for a while. Adding it was relatively easy.
The first step is to provide fallback support for the situation where Jetpack or Photon is not installed or oddly disabled.
/**
* Returns true if Photon from Jetpack is supported.
* @return bool
*/
function convergence_photon_support() {
return class_exists( 'Jetpack' ) &&
method_exists( 'Jetpack', 'get_active_modules' ) &&
in_array( 'photon', Jetpack::get_active_modules() ) &&
function_exists( 'jetpack_photon_url' );
}
This function is straight from the Photon docs. It checks to see if the Jetpack class is loaded, if the methods exist and if Photon exists. All of that is very important, but it would be a shame to run this on every single request (while it’s not intensive, it’s yet more overhead), so I hope you have some page caching somewhere along the line too.
/**
* Returns a Photon based image Photon if Jetpack is enabled and Photon support is on.
* @param $url the URL of the image to be used in Photon
* @return bool
*/
function convergence_villain_photon_image($url) {
$photon = convergence_photon_support();
if (!$photon) return $url;
$url = substr($url, 7); // removes the http:// that photon breaks on
$path = "http://i0.wp.com/$url";
return $path;
}
This function checks if there is Photon support and if not, returns the given URL unchanged. The substr removes the http:// from the URL because Photon prefers to not have it there. (And, if you’re wondering, no, it’s not mentioned anywhere on the documentation page for Photon. Just saying.)
From there, my theme implements these functions in a simple way. On the homepage of The-Nexus.tv, the following code generates the images int the 2-by-3 grid.
<?php
$image = get_the_image(array('size'=>'thumbnail', 'link_to_post'=>false, 'format'=>'array' ));
$image_url = convergence_villain_photon_image($image['url']);
?>
<a href="<?php echo get_permalink(); ?>" title="<?php echo $image['alt']; ?>">
<img src="<?php echo $image_url; ?>" alt="<?php echo $image['alt']; ?>" class="<?php echo $image['class']; ?>" />
</a>
get_the_image is a blessing and a curse from Hybrid, but it is useful nevertheless. I pass in the URL into my fancy-pants function for fetching Photon images and I echo it all over.
Adding Photon is really that easy.
And the name
Photon is clever. Like
Photo.