my alt

Creating a MU Plugin to Modernize the WordPress Caption Shortcode

Discover how to create a Must-Use (MU) plugin to enhance WordPress caption shortcodes using modern image formats like WebP for improved performance and faster loading times.

Why Modernize the Caption Shortcode?

The traditional WordPress caption shortcode outputs images in standard formats, typically JPEG. With the increasing adoption of modern image formats like WebP, which provide better compression and quality, it’s beneficial to serve these formats for better performance and faster loading times. By using the <picture> element, we can deliver the best image format supported by the user’s browser.

Step-by-Step Breakdown

This plugin will enhance the default caption functionality by using the <picture> element, enabling support for modern image formats such as WebP alongside traditional JPEG images. This approach ensures better performance and compatibility across different browsers.

This guide assumes you have some logic implemented separately to generate the modern image formats, as this is not covered in the code.

You can find the full plugin code in our GitHub Repository. In this article we will explain the code used and its benefits.
Let’s delve into the code and understand each part of the plugin.

Plugin Header

The plugin starts with a standard header, providing essential details about the plugin:

 * Plugin Name: Modernize WP Caption ShortCode
 * Description: Customizes the output of the WP caption ShortCode with <picture> element for different formats.
 * Version: 1.0
 * Author: Your Name
 * Author URI:
 * License: GPL3

This section includes metadata such as the plugin name, description, version, author, and license. It helps WordPress identify and manage the plugin.

Security Check

We ensure the code is not accessed directly for security purposes:

if ( ! defined( 'ABSPATH' ) ) {

This check ensures that the file is being executed within the WordPress environment and not accessed directly.

Filter Hook for the Caption Shortcode

We hook into the img_caption_shortcode filter to customize the caption output:

add_filter( 'img_caption_shortcode', 'custom_img_caption_shortcode_with_picture_formats', 10, 3 );

The filter function custom_img_caption_shortcode_with_picture_formats will modify the caption output.

Custom Caption Shortcode Function

The main function responsible for modifying the caption output is defined as follows:

function custom_img_caption_shortcode_with_picture_formats( $output, $attr, $content ) {
    // magic happens here.

Extracting Shortcode Attributes

We extract the shortcode attributes using shortcode_atts:

$atts = shortcode_atts(
		'id'      => '',
		'align'   => '',
		'width'   => '',
		'caption' => '',

This function ensures that all attributes are accounted for, even if they are not explicitly defined in the shortcode.

Handling Empty Captions

If there is no caption, we simply return the content:

if ( empty( $atts['caption'] ) ) {
	return $content;

Cleaning Up Attributes

Next, we clean up the attributes for use in our output:

$id        = $atts['id'] ? ' id="' . esc_attr( $atts['id'] ) . '"' : '';
$align     = ' class="wp-caption ' . esc_attr( $atts['align'] ) . ' img-fluid"';
$max_width = $atts['width'] ? ' style="max-width: ' . (int) $atts['width'] . 'px;"' : ' style="max-width: 100%;"';

Generating the <picture> Element

We generate the <picture> element with different sources for WebP and JPEG formats:

$img_id       = preg_match( '/wp-image-([0-9]+)/i', $content, $matches ) ? $matches[1] : 0;
$image_url    = wp_get_attachment_image_url( $img_id, 'full' );
$image_srcset = wp_get_attachment_image_srcset( $img_id, 'full' );
$image_sizes  = wp_get_attachment_image_sizes( $img_id, 'full' );
$image_webp   = wp_get_attachment_image_src( $img_id, 'full' )[0]; // Assuming you have WebP versions of your images stored similarly

$output  = '<figure' . $id . $align . $max_width . '>';
$output .= '<picture>';
$output .= '<source type="image/webp" srcset="' . esc_url( $image_webp ) . '">';
$output .= '<source type="image/jpeg" srcset="' . esc_url( $image_url ) . '">';
$output .= '<img src="' . esc_url( $image_url ) . '" srcset="' . esc_attr( $image_srcset ) . '" sizes="' . esc_attr( $image_sizes ) . '" alt="' . esc_attr( $atts['caption'] ) . '" class="img-fluid">';
$output .= '</picture>';
$output .= '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption>';
$output .= '</figure>';

Here, we assume that WebP versions of the images are generated and stored similarly to the original images.

Final Output

The function returns the modified caption output:

return $output;

Benefits of Using the Custom Caption Shortcode Plugin

By implementing this MU Plugin, you leverage modern web technologies to improve image delivery and performance on your WordPress site. The <picture> element ensures that the best image format is served based on the browser’s capabilities, reducing load times and enhancing the user experience.

This approach aligns with best practices for web performance and future-proofs your site by adopting modern image formats.

To implement this MU Plugin, create a new PHP file in the wp-content/mu-plugins directory of your WordPress installation and paste the provided code into this file. The plugin will automatically be activated and start enhancing your caption shortcodes with the <picture> element.

Feel free to adapt and expand this code to suit your specific needs, ensuring that your WordPress site remains fast, efficient, and visually appealing.