Limit the available blocks in Gutenberg

written by: Jeff McNear

To date I have only found a way to explicitly allow certain blocks (rather than the selective disallowing of certain blocks) using this addition to the active theme’s function file

//https://rudrastyh.com/gutenberg/remove-default-blocks.html
add_filter( 'allowed_block_types', 'misha_allowed_block_types' );
function misha_allowed_block_types( $allowed_blocks ) {
	return array(
		'core/image',
		'core/paragraph',
		'core/heading',
		'core/list',
		'core/gallery',
		'core/audio',
		'core/code',
		'core/freeform',
		'core/html',
		'core/columns',
		'core/button',
		'core/separator',
		'core/shortcode',
		'core/search',
		'core/table',
		'core/embed',
		'core/spacer',
		'core/group',
	);
}

The potential problem here is that periodically core releases new blocks, and if you add custom blocks or supplemental blocks via a plugin, those block names (and prefixes) need to be added to the code above.

It may be more useful to limit available blocks by post type, the following code will apply restrictions only to posts.

//https://joseph-dickson.com/removing-specific-gutenberg-core-blocks-and-options/
function pz_allowed_block_types( $allowed_block_types, $post ) {
    if ( $post->post_type !== 'post' ) {
        return $allowed_block_types;
    }
    return array( 
	'core/paragraph',
	'core/image',
	'core/gallery',
	'core/html',
	'core/list',
	);
}
add_filter( 'allowed_block_types', 'pz_allowed_block_types', 10, 2 );

In custom post types when you declare the type you need to explicitly enable gutenberg by including this line in the $args = array(

 'show_in_rest'       => true, // To use Gutenberg editor.