Created
July 1, 2025 20:42
-
-
Save michael-sumner/df992d413771c87da3fb474bdb3f9f51 to your computer and use it in GitHub Desktop.
Restrict blocks by post type. With example post type and blocks for post type only.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'allowed_block_types_all', 'restrict_blocks_by_post_type', 10, 2 ); | |
/** | |
* Restrict blocks by post type. | |
* | |
* @param array|bool $allowed_block_types The allowed blocks. | |
* @param WP_Post $post The post object. | |
* @return array|bool | |
* | |
* @since WordPress 6.8.1 | |
*/ | |
public function restrict_blocks_by_post_type( $allowed_block_types, $block_editor_context ) { | |
if ( empty( $block_editor_context->post ) ) { | |
return $allowed_block_types; | |
} | |
// Get the post object. | |
$post = $block_editor_context->post; | |
$post_type = $post->post_type; | |
/* | |
* Check if $allowed_block_types is a boolean true. | |
* If it is, set it to an array of all registered blocks. | |
*/ | |
if ( true === $allowed_block_types && ! is_array( $allowed_block_types ) ) { | |
$allowed_block_types = array_keys( \WP_Block_Type_Registry::get_instance()->get_all_registered() ); | |
} | |
// If we are _not_ in the Event post type, then remove unnecessary blocks from the editor. | |
if ( EventPostType::get_instance()->name !== $post_type ) { | |
$blocks_to_remove = [ | |
'aom/calendar-download', | |
'aom/event-date', | |
'aom/event-full-location', | |
]; | |
// Remove the blocks from the allowed blocks. | |
$allowed_block_types = array_diff( $allowed_block_types, $blocks_to_remove ); | |
$allowed_block_types = array_values( $allowed_block_types ); | |
} | |
return $allowed_block_types; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment