Disable block from editor based on post type


I’ve made a Gutenberg block which is only appropriate to show on hierarchical post types, so I want to disable it from the block inserter for non-hierarchical post types.

I thought about how to achieve this in PHP, but the WordPress documentation on registering blocks seems to suggest that blocks should be registered in PHP on the init hook and not a later hook where you could check if the post being edited is hierarchical. At the time the init hook fires, the currently viewed post is not yet available via e.g. get_post(), so I can’t check its post_type.

I also thought about how to achieve this in the (JavaScript) script that I register with the editor_script property passed to register_block_type, but I don’t know how to check the post type being edited to make it possible to halt the block registration in the case of non-hierarchical post types. It also seems a bit silly to enqueue and run the block script only for the script to decide that it shouldn’t do anything, so ideally I would like to implement this checking in PHP.

Is there some standard way to make a block available only for specific post types, ideally in PHP?

, , , , Sean 3 years 2020-03-25T12:51:04-05:00 0 Answers 167 views 0

Leave an answer