Jeremy Felt

Open source student.

Register a block for a post type

I have a post type that requires a custom block. The post type supports all other blocks, but the block supports only this post type.

What I’d like:

  • Allow this block to be inserted and edited when editing this post type.
  • Do not allow this block to be inserted and edited when editing another post type.
  • Only enqueue the JavaScript for this block when it is used.
  • Render this block on any view it is… uh, rendered.

I can’t use the allowed_block_types_all filter. This is only useful when you have a small, predefined list of blocks you’d like to allow. The default value is true, meaning all. There is no way to remove a single block type.

I can register the block in PHP and then unregister it in JavaScript, but it’s silly to load a bunch of JavaScript that you aren’t using.

There are very long discussions on GitHub that start to cover possible future solutions for this, but no clear answer yet.

What I’ve found:

The cleanest, if somewhat hacky feeling, answer I have so far is:

add_action( 'init', __NAMESPACE__ . '\init' );

function init() {
	// Register the block in PHP.
	$block_type = register_block_type_from_metadata(
		__DIR__,
		[
			'render_callback' => __NAMESPACE__ . '\render',
		]
	);

	// Contextually unregister the editor script that registers the block in JavaScript.
	add_action( 'current_screen', function( \WP_Screen $current_screen ) use ( $block_type ) {
		if ( 'post' === $current_screen->base && 'cpt_slug' !== $current_screen->post_type ) {
			wp_deregister_script( $block_type->editor_script );
		}
	} );
}

I dislike parts of this, but it’s readable enough, simple, and it works. The editor JavaScript is only loaded when editing a specific post type and the block will continue to render whenever it is encountered in the_content.

Responses and reactions

Replies

Leave a Reply

Your email address will not be published. Required fields are marked *

The only requirement for your mention to be recognized is a link to this post in your post's content. You can update or delete your post and then re-submit the URL in the form to update or remove your response from this page.

Learn more about Webmentions.