Filtering Blocks When allowed_block_types_all is a boolean

If you’re trying to filter which blocks are allowed in the WordPress block editor using allowed_block_types_all but the value is true/false it’s difficult to know what to do. I’ll cover every use case here:

add_action( 'allowed_block_types_all', function( $blocks, \WP_Block_Editor_Context $context ) {
// what if $blocks is true/false?
return $blocks;
}, 10, 2 );

If It’s false

This means no blocks are allowed.

  • If you want to remove blocks then you don’t need to do anything and can return early.
  • If you are trying to add blocks, return them as an array
add_action( 'allowed_block_types_all', function( $blocks, \WP_Block_Editor_Context $context ) {
if ( empty( $blocks ) ) {
// I only want this block to be available.
return [ 'myblocks/block' ];
}
return $blocks;
}, 10, 2 );

Note that I’ve used empty here so that it also catches empty arrays as well as false.

If It’s true

This is the default value and means that all blocks are allowed. Unfortunately you can’t filter a boolean, but we can turn this into an array by calling the block registry:

add_action( 'allowed_block_types_all', function( $blocks, \WP_Block_Editor_Context $context ) {
if ( empty( $blocks ) ) {
return $blocks;
}

// If all blocks are enabled, generate a new list we can filter.
if ( true === $blocks ) {
$types = \WP_Block_Type_Registry::get_instance()->get_all_registered();
$blocks = wp_list_pluck( $types, 'name' );
}

// continue as usual..

return $blocks;
}, 10, 2 );

Here we’re using \WP_Block_Type_Registry::get_instance()->get_all_registered() to get an array of WP_Block-Type objects, then extracting their names with wp_list_pluck ( a foreach or array_map would also work but this is neater ).

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.