How to Create Your Own Image Optimization Plugin by Leveraging Jetpack’s Photon

on in Blog
Last modified on

This is a quick code tutorial detailing how to leverage Jetpack’s Photon for custom images.

Not all images in your theme or plugin or custom theme functionality will be inserted via WordPress methods.

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.

https://developer.wordpress.com/docs/photon/

For custom code such as images coming from custom post meta fields or Advanced Custom Fields values, we’ll use a custom function.

Say we have the following code snippet:

<?php
$myImage = get_post_meta($post->ID, 'my_image_meta', true);

$out = '<img src="' . $myImage . '" alt="Some description" loading="lazy">';

return $out;

We’ll use the function below, where we check if the Jetpack plugin is active and if the Photon module is enabled.

<?php
function wppd_image_downsize($imageUri, $downsize = false, $args = []) {
    /**
     * Jetpack Photon
     * 
     * @docs https://developer.wordpress.com/docs/photon/
     */
     if (function_exists('jetpack_photon_url')) {
        if (class_exists('Jetpack') && Jetpack::is_module_active('photon')) {
            $imageUri = jetpack_photon_url($imageUri, $args, null);
        }
    }

    return $imageUri;
}

The image snippet above becomes:

<?php
$myImage = get_post_meta($post->ID, 'my_image_meta', true);
$myImage = wppd_image_downsize($myImage);

$out = '<img src="' . $myImage . '" alt="Some description" loading="lazy">';

return $out;

And now the image is served from wp.com’s CDN. Check the official Jetpack documentation for additional arguments, such as size, cropping, quality and filters.

Also see the Photon API page for more detailed explanations and examples.

Related posts