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?
3 Answers
You can use the allowed_block_types
hook:
<?php
function wpse_allowed_block_types($allowed_block_types, $post) {
// Limit blocks in 'post' post type
if($post->post_type == 'post') {
// Return an array containing the allowed block types
return array(
'core/paragraph',
'core/heading'
);
}
// Limit blocks in 'page' post type
elseif($post->post_type == 'page') {
return array(
'core/list'
);
}
// Allow defaults in all other post types
else {
return $allowed_block_types;
}
}
add_filter('allowed_block_types', 'wpse_allowed_block_types', 10, 2);
?>
Tweak with as many or as few conditions as you need. You can also enable non-Core blocks by identifying their namespace and name and putting those in the array.