Using WordPress ‘image_add_caption_text’ PHP filter

The image_add_caption_text WordPress PHP Filter allows you to modify the caption text of an image before it’s displayed.

Usage

add_filter( 'image_add_caption_text', 'your_custom_function', 10, 2 );
function your_custom_function( $caption, $id ) {
    // your custom code here
    return $caption;
}

Parameters

  • $caption (string): The original caption text.
  • $id (int): The attachment ID.

More information

See WordPress Developer Resources: image_add_caption_text

Examples

Add a copyright notice to image captions, preserving the original caption text.

add_filter( 'image_add_caption_text', 'add_copyright_notice', 10, 2 );
function add_copyright_notice( $caption, $id ) {
    $copyright = ' © ' . date('Y') . ' Your Company Name.';
    return $caption . $copyright;
}

Remove Special Characters from Captions

Remove special characters from image captions to improve accessibility.

add_filter( 'image_add_caption_text', 'remove_special_characters', 10, 2 );
function remove_special_characters( $caption, $id ) {
    $clean_caption = preg_replace( '/[^a-zA-Z0-9\s]/', '', $caption );
    return $clean_caption;
}

Add Image File Name as Caption

If the caption is empty, use the image file name as the caption.

add_filter( 'image_add_caption_text', 'use_image_filename', 10, 2 );
function use_image_filename( $caption, $id ) {
    if ( empty( $caption ) ) {
        $attachment = get_post( $id );
        $caption = $attachment->post_title;
    }
    return $caption;
}

Add Alt Text as Caption

If the caption is empty, use the image alt text as the caption.

add_filter( 'image_add_caption_text', 'use_image_alt_text', 10, 2 );
function use_image_alt_text( $caption, $id ) {
    if ( empty( $caption ) ) {
        $caption = get_post_meta( $id, '_wp_attachment_image_alt', true );
    }
    return $caption;
}

Add Custom Prefix to Image Captions

Add a custom prefix to all image captions.

add_filter( 'image_add_caption_text', 'add_custom_prefix', 10, 2 );
function add_custom_prefix( $caption, $id ) {
    $prefix = 'Image: ';
    return $prefix . $caption;
}