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:
- Allow/deny block use based on post-type or template context
- A brief note on Introduce Child Blocks
- Limit Block to Certain Post Type(s)
- Adding option in registerBlockType function to specify post_types to restrict a block from appearing everywhere
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
It’s funny how quickly something goes from “yeah, I think this should work even if it feels a bit hacky” to used on every in-progress project.
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.