Apply JetPack Photon To Advanced Custom Fields Images

I have already covered in previous posts how useful JetPack Photon is for website performance, however there are some instances where it falls short. In short, JetPack Photon rewrites your website’s images and serves them from their own content delivery network (CDN). If you do not know what a CDN is, please refer to this post where I explain the basics of a CDN. Photon does not rewrite images added with Advanced Custom Fields. This can lead to many images being ignored by JetPack Photon, therefore you miss out on all the benefits.

I encountered this recently working on a clients site where their images were added via Advanced Custom Fields. After fiddling with the bit, I found a workaround. Albeit, it is a bit retroactive and you will need to modify the code. This will work whether you are using JetPack or not.

After modifying the code, you will add this code to your functions.php file. Modify the below code with your domain name. I showed you an example using this domain name below.

function cdn_attachments_urls($url, $post_id) {
return str_replace('your-domain-here/wp-content/uploads', 'https://i0.wp.com/your-domain-here-without-http-https/wp-content/uploads', $url);
}
add_filter('acf/format_value/type=image', 'cdn_attachments_urls', PHP_INT_MAX, 2);

Here is the example using my domain name.

function cdn_attachments_urls($url, $post_id) {
return str_replace('your-domain-here/wp-content/uploads', 'https://i0.wp.com/your-domain-here-without-http-https/wp-content/uploads', $url);
}
add_filter('acf/format_value/type=image', 'cdn_attachments_urls', PHP_INT_MAX, 2);

The code is very straightforward. It replaces any image in the image field type. To do this, replace the bolded code above with your domain name.

In the future, I may look into modifying the code so you can paste it the functions.php file without modification. For now, this is an easy way to apply JetPack Photon to Advanced Custom Fields images.

scott hartley

About the author

Scott is a web performance geek, lover of all things coffee, and avid video game player. His WordPress work delves into web performance, web security, and SEO.

Leave a Comment