The code below will only run once whenever a file is uploaded.
- We keep an array (
$image_mimes
) of acceptable image-mimetypes - We get the current attachment mime type
- We make sure what is given is indeed an image ( because we don’t need unnecessary postmeta cluttering our table )
- We grab the title from the attachment and set it to the alt-text initially
After that the user can update it however they wish ( or remove it entirely ):
function add_image_alt( $attachment_id ) {
$image_mimes = array( 'image/jpeg', 'image/gif', 'image/png', 'image/bmp', 'image/tiff', 'image/x-icon' );
$attachment_type = get_post_mime_type( $attachment_id );
if( in_array( $attachment_type, $image_mimes ) ) {
$attachment_title = get_the_title( $attachment_id );
update_post_meta( $attachment_id, '_wp_attachment_image_alt', sanitize_text_field( $attachment_title ) );
}
}
add_action( 'add_attachment', 'add_image_alt' );