Block Publishing Until Every Image Has Alt Text
Disables the Publish and Update buttons in the block editor while any image block is missing alternative text, and shows a notice explaining why.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-alt-lock', '', array( 'wp-data', 'wp-editor', 'wp-notices' ), null, true );
wp_enqueue_script( 'wpide-alt-lock' );
wp_add_inline_script( 'wpide-alt-lock', <<<'JS'
(function (wp) {
var locked = false;
function missingAlt(blocks) {
return blocks.some(function (b) {
var noAlt = b.name === 'core/image' && b.attributes.url && !(b.attributes.alt || '').trim();
return noAlt || (b.innerBlocks && missingAlt(b.innerBlocks));
});
}
wp.data.subscribe(function () {
var blocks = wp.data.select('core/block-editor').getBlocks();
var missing = missingAlt(blocks);
if (missing === locked) { return; }
locked = missing;
var editor = wp.data.dispatch('core/editor');
var notices = wp.data.dispatch('core/notices');
if (missing) {
editor.lockPostSaving('wpide-alt');
notices.createNotice('warning', 'Add alternative text to every image before publishing.', { id: 'wpide-alt', isDismissible: false });
} else {
editor.unlockPostSaving('wpide-alt');
notices.removeNotice('wpide-alt');
}
});
})(window.wp);
JS
);
} );
Notes
Strict by design; for decorative images type a short description anyway or use the pre-publish warning snippet instead.
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.