Using WordPress ‘image_add_caption_shortcode’ PHP filter

The image_add_caption_shortcode WordPress PHP Filter allows you to modify the image HTML markup including the caption shortcode.

Usage

add_filter('image_add_caption_shortcode', 'your_function_name', 10, 2);
function your_function_name($shcode, $html) {
    // your custom code here
    return $shcode;
}

Parameters

  • $shcode (string): The image HTML markup with caption shortcode.
  • $html (string): The original image HTML markup.

More information

See WordPress Developer Resources: image_add_caption_shortcode

Examples

Add a CSS class to the caption

This example adds a custom CSS class “custom-caption” to the caption shortcode.

add_filter('image_add_caption_shortcode', 'add_custom_caption_class', 10, 2);
function add_custom_caption_class($shcode, $html) {
    $shcode = str_replace('class="wp-caption', 'class="wp-caption custom-caption', $shcode);
    return $shcode;
}

Remove width attribute from caption

This example removes the width attribute from the caption shortcode.

add_filter('image_add_caption_shortcode', 'remove_caption_width', 10, 2);
function remove_caption_width($shcode, $html) {
    $shcode = preg_replace('/width="\d+"/', '', $shcode);
    return $shcode;
}

Change caption text color

This example changes the caption text color to red.

add_filter('image_add_caption_shortcode', 'change_caption_text_color', 10, 2);
function change_caption_text_color($shcode, $html) {
    $shcode = str_replace('<p class="wp-caption-text">', '<p class="wp-caption-text" style="color:red;">', $shcode);
    return $shcode;
}

Add a custom wrapper around caption

This example adds a custom div wrapper around the caption.

add_filter('image_add_caption_shortcode', 'add_custom_wrapper_around_caption', 10, 2);
function add_custom_wrapper_around_caption($shcode, $html) {
    $shcode = '<div class="custom-wrapper">' . $shcode . '</div>';
    return $shcode;
}

Add an ID attribute to the caption

This example adds an ID attribute to the caption shortcode.

add_filter('image_add_caption_shortcode', 'add_id_to_caption', 10, 2);
function add_id_to_caption($shcode, $html) {
    $shcode = str_replace('<div class="wp-caption', '<div id="my-caption" class="wp-caption', $shcode);
    return $shcode;
}