Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.