Accessibility PHP Intermediate

Warn About Images Without Alt Text in the Editor

Show a warning in the block editor listing images that have no alt text, so writers can fix them before publishing.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 39 lines
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 }
					);
				}
			} );
		} )();"
	);
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • It’s a reminder, not a block: writers can still publish. Decorative images can correctly have empty alt text.
  • Only Image blocks are checked, not galleries, covers or images inside HTML blocks.

How to test it

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.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only