Skip to content

Instantly share code, notes, and snippets.

@dominicfallows
Last active May 7, 2017 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dominicfallows/457334ef84e3a805f7201fd8762ce569 to your computer and use it in GitHub Desktop.
Save dominicfallows/457334ef84e3a805f7201fd8762ce569 to your computer and use it in GitHub Desktop.
Function to fix a problem with Photon (Jetpack module from WordPress/Automattic) ignoring image crops that are made through the CMS (with plugins like https://wordpress.org/plugins/manual-image-crop/).
/**
* Get URL of an Editor cropped (manual or automatic) version of an image (and get Photon URL if wanted)
* https://gist.github.com/dominicfallows/457334ef84e3a805f7201fd8762ce569
*
* @param integer $imgID The attachment media ID
* @param string $size (optional) The registered image size you want. Default 'full'
* @param bool $photon_if_available (optional) If Photon is available, return the Photon-ized URL Default true
* @return string
*/
function get_image_url($imgID, $size = 'full', $photon_if_available = true) {
// Is Photon available and not in development mode
$photon_if_available = class_exists('Jetpack') && method_exists('Jetpack', 'get_active_modules') && in_array('photon', Jetpack::get_active_modules()) && !Jetpack::is_development_mode();
// If Jetpack is installed, Photon is active and we're not in development mode - then disable Photon
if($photon_if_available) {
$photon_removed = remove_filter( 'image_downsize', array( Jetpack_Photon::instance(), 'filter_image_downsize' ) );
}
// Get the local URL of the Editor cropped (manual or automatic) version of the image
$local_img_src = wp_get_attachment_image_src ($imgID, $size);
// If we've previously disabled Photon, renable it
if($photon_removed) {
add_filter( 'image_downsize', array( Jetpack_Photon::instance(), 'filter_image_downsize' ), 10, 3 );
}
// If we want to, now Photon-ize the image, otherwise keep the local url
$img_url = $photon_if_available ? jetpack_photon_url($local_img_src[0]) : $local_img_src[0];
return $img_url;
}
@dominicfallows
Copy link
Author

Add this function to your themes function.php or your plugin includes to use it in place of other image retrieval functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment