Report Images Missing Alt Text (WP-CLI)
Adds a "wp missing-alt" command that lists every image in the Media Library without alt text, with the post it is attached to, so you can fix accessibility gaps in order of importance.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'missing-alt', function ( $args, $assoc_args ) {
global $wpdb;
$rows = $wpdb->get_results(
"SELECT p.ID, p.post_title, p.post_parent FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} m ON m.post_id = p.ID AND m.meta_key = '_wp_attachment_image_alt'
WHERE p.post_type = 'attachment' AND p.post_mime_type LIKE 'image/%' AND ( m.meta_value IS NULL OR m.meta_value = '' )
ORDER BY p.post_parent DESC, p.ID DESC"
);
if ( ! $rows ) {
WP_CLI::success( 'Every image has alt text.' );
return;
}
$items = array();
foreach ( $rows as $row ) {
$items[] = array(
'ID' => $row->ID,
'title' => $row->post_title,
'file' => wp_basename( (string) get_attached_file( $row->ID ) ),
'attached_to' => $row->post_parent ? get_the_title( $row->post_parent ) . ' (#' . $row->post_parent . ')' : '-',
);
}
WP_CLI\Utils\format_items( $assoc_args['format'] ?? 'table', $items, array( 'ID', 'title', 'file', 'attached_to' ) );
}, array(
'shortdesc' => 'Lists images that have no alt text.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'format', 'optional' => true, 'default' => 'table', 'options' => array( 'table', 'csv', 'json', 'count', 'ids' ) ),
),
) );
Notes
Use --format=csv > missing-alt.csv to hand the list to an editor.
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.