Using WordPress ‘img_caption_shortcode’ PHP filter

The img_caption_shortcode WordPress PHP Filter allows you to customize the default caption shortcode output for images in your posts.

Usage

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

function your_custom_function($output, $attr, $content) {
    // your custom code here
    return $output;
}

Parameters

  • $output (string): The default caption output, initially empty.
  • $attr (array): Attributes of the caption shortcode.
  • $content (string): The image element, possibly wrapped in a hyperlink.

More information

See WordPress Developer Resources: img_caption_shortcode

Examples

Add a CSS class to the caption container

This example adds a custom CSS class to the caption container.

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

function add_custom_caption_class($output, $attr, $content) {
    return '<div class="custom-caption">' . $content . '</div>';
}

Modify the caption text

This example appends custom text to the caption.

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

function modify_caption_text($output, $attr, $content) {
    $caption = isset($attr['caption']) ? $attr['caption'] : '';
    $new_caption = $caption . ' - Custom Text';
    return str_replace($caption, $new_caption, $output);
}

Wrap the image in a custom container

This example wraps the image in a custom container with a specific CSS class.

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

function wrap_image_custom_container($output, $attr, $content) {
    return '<div class="custom-image-container">' . $content . '</div>';
}

Add an icon to the caption

This example adds an icon to the beginning of the caption.

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

function add_icon_to_caption($output, $attr, $content) {
    $caption = isset($attr['caption']) ? $attr['caption'] : '';
    $icon = '<i class="fas fa-camera"></i> ';
    $new_caption = $icon . $caption;
    return str_replace($caption, $new_caption, $output);
}

This example removes the hyperlink from the image element within the caption.

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

function remove_image_hyperlink($output, $attr, $content) {
    return preg_replace('/<a[^>]*>|<\/a>/', '', $content);
}