Pre-Publish Warning for Images Without Alt Text
Shows a panel in the block editor's pre-publish check listing every image block that has no alternative text, with a button to jump to each one.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-alt-check', '', array( 'wp-plugins', 'wp-editor', 'wp-element', 'wp-data', 'wp-components', 'wp-block-editor' ), null, true );
wp_enqueue_script( 'wpide-alt-check' );
wp_add_inline_script( 'wpide-alt-check', <<<'JS'
(function (wp) {
var el = wp.element.createElement;
var Panel = (wp.editor && wp.editor.PluginPrePublishPanel) || (wp.editPost && wp.editPost.PluginPrePublishPanel);
if (!Panel) { return; }
function collect(blocks, out) {
blocks.forEach(function (b) {
if ((b.name === 'core/image' || b.name === 'core/media-text' || b.name === 'core/cover') && !(b.attributes.alt || '').trim() && (b.attributes.url || b.attributes.mediaUrl)) {
out.push(b);
}
if (b.innerBlocks && b.innerBlocks.length) { collect(b.innerBlocks, out); }
});
return out;
}
function AltPanel() {
var missing = wp.data.useSelect(function (select) { return collect(select('core/block-editor').getBlocks(), []); }, []);
var select = wp.data.useDispatch('core/block-editor').selectBlock;
return el(Panel, { title: 'Image alt text', initialOpen: missing.length > 0 },
missing.length === 0 ? el('p', null, 'Every image has alternative text.') :
el('div', null,
el('p', null, missing.length + ' image(s) have no alternative text:'),
missing.map(function (b, i) {
return el(wp.components.Button, { key: b.clientId, variant: 'link', onClick: function () { select(b.clientId); } }, 'Image ' + (i + 1));
})
)
);
}
wp.plugins.registerPlugin('wpide-alt-check', { render: AltPanel });
})(window.wp);
JS
);
} );
Notes
Images that are purely decorative can stay without alt text; the panel is a reminder and does not block publishing.
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.