skip to Main Content

In gutenberg/block-editor, how can I check whether I’ve already registered a block type? Is there a function I can use? Searching through the Block Editor Handbook I couldn’t see a function to check this.

An example of what I am trying to do is below:

class My_Block {

    public function __construct() {
        if ( ! SOME_FUNCTION_block_exists('foo/column') ) {
            register_block_type( 'foo/column', my_args );
        }
    }
    
}

2

Answers


  1. In WordPress Gutenberg, using JavaScript you can check if a block exists by name with getBlockType(), eg:

    JavaScript

    import { getBlockType } from '@wordpress/blocks';
    import { registerBlockType } from '@wordpress/blocks';
    
        if (!getBlockType('foo/column')) {
            registerBlockType('foo/column', {
                edit: Edit,
                save,
            });
        }
    

    While the above is probably the prefered way, there is a valid case for checking in PHP if a block is already registered, eg. if you want to add a render callback for a block with server side rendering. While I haven’t seen a core function for this, I’ve found a way it can be done by using the REST API endpoint for block-types to search for the block by namespace/name:

    PHP

    class My_Block
    {
    
        public function __construct()
        {
            if (! is_block_registered('foo/column')) {
                register_block_type('foo/column', $args);
            }
        }
    
        private function is_block_registered($block_name)
        {
            // Use REST API to query if block exists by <namespace>/<name>
            $route = new WP_REST_Request('GET', '/wp/v2/block-types/' . $block_name);
            $request = rest_do_request($route);
    
            if ($request->status == 404) {
                // Block is not found/registered
                return false;
            }
            // Block is registered (status is 200)
            return true;
        }
    }
    
    Login or Signup to reply.
  2. There is the method ´is_registered()´ in the class ´WP_Block_Type_Registry´ (that class handles the registration of blocks). See the docs: https://developer.wordpress.org/reference/classes/wp_block_type_registry/is_registered/

    class My_Block {
    
        public function __construct() {
            if ( ! WP_Block_Type_Registry::get_instance()->is_registered( 'foo/column' ) ) {
                register_block_type( 'foo/column', my_args );
            }
        }
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search