Posted on Leave a comment

How to disable the “Edit as HTML” option on the WordPress block editor

The WordPress block editor, or Gutenberg, is a very powerful content editor for both your content and your site as a whole, if you’re using a Full Site Editing enabled theme.

But how much power is enough power? Should we be able to directly edit a block HTML? We don’t think so.

TL;DR? Know how to disable HTML Block editing on your website.

Why shouldn’t we have access to directly edit HTML on a Gutenberg block?

Here’s how an image block is stored as HTML on the database:

<!-- wp:image {"id":15456,"width":"200px","sizeSlug":"full","linkDestination":"none","className":"someclass"} -->
<figure class="wp-block-image size-full is-resized someclass">
	<img src="https://wordpress.local/wp-content/uploads/2019/01/V0101125_295303.jpg" alt="" class="wp-image-15456" style="width:200px"/>
</figure>
<!-- /wp:image -->Code language: HTML, XML (xml)

See that HTML comment before the actual HTML? There’s important JSON encoded information used by the block editor there, like the width or the class name, for example.

If you directly edit this block HTML and change any value that is also referred to in this comment, most likely the block will break and you’ll be greeted with the “This block contains unexpected or invalid content” message.

So, even if you (think that) know what you’re doing, directly editing the HTML of a block is never a good idea, and this should probably be disabled on every website you own.

PHP snippet to disable Block HTML editing on your website

To disable HTML editing on the WordPress block editor, we’re using the block_editor_settings_all filter, which filters the settings to pass to the block editor for all editor types, like this:

<?php
add_filter( 'block_editor_settings_all', function( $settings ) {
	$settings['codeEditingEnabled'] = false;
	return $settings;
} );Code language: HTML, XML (xml)

Or you can allow administrators, although we do not recommend it.

<?php
add_filter( 'block_editor_settings_all', function( $settings ) {
	$settings['codeEditingEnabled'] = current_user_can( 'manage_options' );
	return $settings;
} );Code language: HTML, XML (xml)

Use this PHP snippet on your (child-)theme functions.php file or in your favorite PHP snippets plugin.

Do you already know our plugins?

All our WordPress and WooCommerce plugins are crafted with simplicity of configuration, lightweightness and being developer friendly in mind.

Get to know them here.

Leave a Reply