How can I require users to enter alt text when adding attachments?

Alt text is surprisingly buried; the only way I’ve been able to retrieve the alt text at all is via the wp_get_attachment_image() function, thusly:

add_filter('wp_insert_attachment_data', 'print_metadata', 10, 2);
function print_metadata( $data, $uncleaned_data ) {

  $attachment_id = $arr['ID'];
  $meta = wp_get_attachment_image($attachment_id);
  error_log($meta);

}

Which produces just some crappy HTML:

<img width="150" height="150" src="https://domain.local/wp-content/uploads/2016/05/cat2-1-150x150.jpg" class="attachment-thumbnail size-thumbnail" alt="My alt text" />

So, I might parse this HTML, after which I might try and throw some sort of validation error. This seems quite hacky, and may also be bad UX (since it would not decorate the Alt Text field itself with a “required” asterisk or anything).

I really wish I could just use the filter above, wp_insert_attachment_data, and just reject any array without alt text; alas, alt text is not in either $data or $uncleaned_data. Or apparently anywhere else for that matter.

Any other ideas? Here’s a picture of the interface:

WP interface

1 Answer
1

The code below will only run once whenever a file is uploaded.

  1. We keep an array ( $image_mimes ) of acceptable image-mimetypes
  2. We get the current attachment mime type
  3. We make sure what is given is indeed an image ( because we don’t need unnecessary postmeta cluttering our table )
  4. 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' );

Leave a Reply

Your email address will not be published. Required fields are marked *