Skip to main content
Login Join
Snippet · PHP

Automatically Copy Featured Image Alt Text to Image Caption

Shared by Amit Dholiya · August 5, 2026 · @wp_insert_attachment_data

13 views
2 upvotes
Back to Snippets

Keeping image captions and alt text consistent can save time when managing media. This snippet automatically copies the image’s Alt Text to its Caption if the caption is empty when the attachment is saved.

Steps

  1. Open your active theme’s functions.php file or a custom functionality plugin.
  2. Add the code below.
  3. Save the file.
  4. Edit or upload an image with Alt Text but no Caption. The Caption will automatically be filled with the Alt Text.
/**
 * Copy image Alt Text to Caption if the Caption is empty.
 */
function wpfolks_copy_alt_to_caption( $post, $attachment ) {

    if ( 'attachment' !== $post['post_type'] ) {
        return $post;
    }

    if ( ! empty( $post['post_excerpt'] ) ) {
        return $post;
    }

    $alt = get_post_meta( $post['ID'], '_wp_attachment_image_alt', true );

    if ( ! empty( $alt ) ) {
        $post['post_excerpt'] = sanitize_text_field( $alt );
    }

    return $post;
}
add_filter( 'wp_insert_attachment_data', 'wpfolks_copy_alt_to_caption', 10, 2 );
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments