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

👋 Ciprian on Tuesday, February 9, 2021 in Blog
Last modified on Tuesday, February 9, 2021

Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

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 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.

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:

$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.

function wppd_image_downsize($imageUri, $downsize = false, $args = []) {
     * Jetpack Photon
     * @docs
     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:

$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’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.

Buy me a coffee to support my work!

👋 Added by Ciprian on Tuesday, February 9, 2021 in Blog. Last modified on Tuesday, February 9, 2021.

Leave a Reply

You have to agree to the comment policy.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Privacy Policy