Skip to content

Allow/deny block use based on post-type or template context #41062

@boonebgorges

Description

@boonebgorges

What problem does this address?

It's sometimes desirable to limit blocks to certain post-type contexts (or, in a parallel fashion, to prevent a specific block from being used in a given context). As far as I can see, the current recommendation is to use unregisterBlockType() to unregister a given block based on getCurrentPostType(), etc. See eg #27607.

While the semantics of this technique are not entirely straightforward ("unregister" rather than "hide", or better still, "prevent from showing in this context"), it pretty much works in the post editor. However, it's not workable in the Site Editor. It's possible to fetch the currently edited template using wp.data.select( 'core/edit-site' ).getEditedPostId(), and to unregisterBlockType() based on this. But it's possible to switch the currently-edited template without a page reload, meaning that you'd have to re-registerBlockType(). Moreover, setting up a subscribe() callback for getEditedPostId() to determine the current context is pretty clumsy.

What is your proposed solution?

I propose that, as part of their registration metadata, a block can specify allow or deny contexts. Maybe something like:

allowForPostTypes: [ 'post', 'page', 'my_custom_post_type' ],
allowForTemplates: [ 'archive', 'single', 'page', 'archive-my_custom_post_type', 'single-my_custom_post_type' ],

postTypes would specify the contexts for the post editor, while templates would be for the site editor. Or it might be better to have a single declaration that covers both cases, depending on the overall strategy for merging the editing experience.

Similarly, it might be nice to have deny declarations that work similarly (though of course there are problems with allowing both).

Apologies in advance if this idea's already in circulation - I searched but couldn't find anything.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Developer ExperienceIdeas about improving block and theme developer experience[Feature] Block APIAPI that allows to express the block paradigm.[Feature] Site EditorRelated to the overarching Site Editor (formerly "full site editing")[Focus] Blocks AdoptionFor issues that directly impact the ability to adopt features of Gutenberg.[Status] In ProgressTracking issues with work in progress[Type] EnhancementA suggestion for improvement.

    Type

    No type

    Projects

    Status

    In Progress

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions