Show a warning in the block editor listing images that have no alt text, so writers can fix them before publishing.
add_action( 'enqueue_block_editor_assets', function (): void {
wp_add_inline_script(
'wp-edit-post',
"( function () {
var last = -1;
function missing( blocks ) {
var n = 0;
blocks.forEach( function ( b ) {
if ( b.name === 'core/image' && b.attributes.url && ! ( b.attributes.alt || '' ).trim() ) {
n++;
}
if ( b.innerBlocks && b.innerBlocks.length ) {
n += missing( b.innerBlocks );
}
} );
return n;
}
wp.data.subscribe( function () {
var editor = wp.data.select( 'core/block-editor' );
if ( ! editor ) {
return;
}
var n = missing( editor.getBlocks() );
if ( n === last ) {
return;
}
last = n;
var notices = wp.data.dispatch( 'core/notices' );
notices.removeNotice( 'nahnu-missing-alt' );
if ( n > 0 ) {
notices.createWarningNotice(
n + ( n === 1 ? ' image has' : ' images have' ) + ' no alt text. Describe each image in the block settings, or leave it empty only if it is decorative.',
{ id: 'nahnu-missing-alt', isDismissible: true }
);
}
} );
} )();"
);
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
Alt text is easiest to add while writing, but the editor doesn’t remind anyone. This snippet shows a warning at the top of the editor whenever images are missing alt text, and updates it as they’re fixed.
The script watches the editor’s blocks through wp.data.subscribe(). Each time something changes, it counts Image blocks, including ones inside groups and columns, that have an image but no alt text.
When the count changes, it replaces the notice with an up-to-date one. When every image has alt text, the notice disappears.
Add an Image block and upload a picture without alt text. A yellow warning should appear. Add alt text in the sidebar and it should go away.