Skip to content

Instantly share code, notes, and snippets.

@jreviews
Last active July 29, 2020 16:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jreviews/b03d06c8058f1043abf0bae4feafec3d to your computer and use it in GitHub Desktop.
Save jreviews/b03d06c8058f1043abf0bae4feafec3d to your computer and use it in GitHub Desktop.
Developer filter to generate thumbnails with the CloudFlare Image CDN
<?php
defined('MVC_FRAMEWORK') or die;
/**
* Re-writes image URLs to the CloudFlare Image CDN
* https://developers.cloudflare.com/images/about/
*/
function jreviews_cloudflare_cdn_thumbnails ($attr, $params = [])
{
// Skip if thumbnails are not yet generated
if (
false !== strpos($attr['src'], 'admin-ajax.php')
||
false !== strpos($attr['src'], 'com_jreviews')
) {
return $attr;
}
if ( false === strpos($attr['src'], 'thumbnail') )
{
return $attr;
}
$width = !empty($attr['width']) ? $attr['width'] : 640;
$attr['src'] = str_replace(WWW_ROOT, WWW_ROOT."cdn-cgi/image/width={$width},quality=100,metadata=copyright,f=auto,fit=scale-down/", $attr['src']);
// Replace '/thumbnail/' with '/original/' and remove thumbnail size
$attr['src'] = preg_replace('/\/thumbnail\/[\s\S]+?\//', '/original/', $attr['src']);
return $attr;
}
Clickfwd\Hook\Filter::add('image_attributes_before_render', 'jreviews_cloudflare_cdn_thumbnails', $priority = 5);
@jreviews
Copy link
Author

jreviews commented Mar 4, 2020

The filter allows modifying the local stored image URLs to load them from a different domain when using a CDN (e.g. CloudFlare)

To use this filter:

  1. Upload the above file to jreviews_overrides/filters
  2. Add the line below to jreviews_overrides/filter_functions.php, if you are not using filters yet, read the documentation on Getting Started with JReviews developer filters
require_once "cloudflare_thumbnails.php";
  1. Check the available URL parameters from CloudFlare's documentation and make any changes you need.

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