Content & Posts PHP Intermediate

Require a Featured Image Before Publishing

Disable the Publish button in the block editor until a featured image is set, with a notice telling the writer why.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 28 lines
add_action( 'enqueue_block_editor_assets', function (): void {
	if ( 'post' !== get_current_screen()?->post_type ) {
		return;
	}

	wp_add_inline_script(
		'wp-edit-post',
		"( function () {
			var locked = false;
			wp.data.subscribe( function () {
				var editor = wp.data.select( 'core/editor' );
				if ( ! editor ) {
					return;
				}
				var missing = ! editor.getEditedPostAttribute( 'featured_media' );
				if ( missing && ! locked ) {
					locked = true;
					wp.data.dispatch( 'core/editor' ).lockPostSaving( 'nahnu-featured-image' );
					wp.data.dispatch( 'core/notices' ).createWarningNotice( 'Add a featured image before publishing.', { id: 'nahnu-featured-image', isDismissible: false } );
				} else if ( ! missing && locked ) {
					locked = false;
					wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'nahnu-featured-image' );
					wp.data.dispatch( 'core/notices' ).removeNotice( 'nahnu-featured-image' );
				}
			} );
		} )();"
	);
} );

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.

If every post needs a featured image, for your blog grid or social sharing, the most reliable fix is to make publishing impossible without one. This snippet does that in the block editor.

How it works

The block editor keeps the post’s current values in its core/editor data store. The script watches for changes, and while featured_media is empty it calls lockPostSaving(), which disables the Publish and Save buttons, and shows a warning notice.

As soon as an image is set, the lock and the notice are removed.

Things to watch

  • Saving drafts is also locked until an image is set. Autosave still runs in the background, so no work is lost.
  • This is a check in the editor only. Posts created through the REST API, imports or the classic editor aren’t blocked.
  • Pairs well with “Set the First Image as the Featured Image” for older posts.

How to test it

Create a new post without a featured image. The Publish button should be disabled and a warning shown. Set an image and the button should work.

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