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
- Open your active theme’s
functions.phpfile or a custom functionality plugin. - Add the code below.
- Save the file.
- 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 );