Alt Text Editor for Images Missing a Description
Adds Media > Alt Text Editor, a page that lists images without alternative text with a thumbnail and a text field next to each, so you can describe dozens of images quickly and save them all at once.
Opens WPIDE on
Code
add_action( 'admin_menu', function () {
add_media_page( 'Alt Text Editor', 'Alt Text Editor', 'upload_files', 'wpide-alt-editor', function () {
if ( isset( $_POST['wpide_alt'] ) && check_admin_referer( 'wpide_alt_editor' ) ) {
$saved = 0;
foreach ( (array) wp_unslash( $_POST['wpide_alt'] ) as $id => $alt ) {
$id = absint( $id );
$alt = sanitize_text_field( $alt );
if ( $id && '' !== $alt && current_user_can( 'edit_post', $id ) ) {
update_post_meta( $id, '_wp_attachment_image_alt', $alt );
$saved++;
}
}
printf( '<div class="notice notice-success"><p>%s</p></div>', esc_html( sprintf( 'Saved alt text for %d image(s).', $saved ) ) );
}
$images = get_posts( array(
'post_type' => 'attachment',
'post_mime_type' => 'image',
'post_status' => 'inherit',
'posts_per_page' => 40,
'no_found_rows' => true,
'meta_query' => array(
'relation' => 'OR',
array( 'key' => '_wp_attachment_image_alt', 'compare' => 'NOT EXISTS' ),
array( 'key' => '_wp_attachment_image_alt', 'value' => '' ),
),
) );
echo '<div class="wrap"><h1>Alt Text Editor</h1>';
if ( ! $images ) {
echo '<p>Every image has alternative text.</p></div>';
return;
}
echo '<p>Describe what each image shows or what it is for. Leave purely decorative images empty.</p><form method="post">';
wp_nonce_field( 'wpide_alt_editor' );
echo '<table class="widefat striped"><thead><tr><th style="width:110px">Image</th><th>Alt text</th></tr></thead><tbody>';
foreach ( $images as $image ) {
printf(
'<tr><td>%1$s</td><td><label class="screen-reader-text" for="wpide-alt-%2$d">Alt text for %3$s</label><input type="text" class="large-text" id="wpide-alt-%2$d" name="wpide_alt[%2$d]" placeholder="%3$s"><p class="description">%4$s</p></td></tr>',
wp_get_attachment_image( $image->ID, array( 96, 96 ) ),
(int) $image->ID,
esc_attr( $image->post_title ),
esc_html( wp_basename( (string) get_attached_file( $image->ID ) ) )
);
}
echo '</tbody></table>';
submit_button( 'Save alt text' );
echo '</form></div>';
} );
} );
Notes
Shows 40 images per page, newest first; leave a field empty to skip that image.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.