Do you check block type with
has_block() to conditionally load scripts, styles, or any other custom logic for the block editor as I do? I’m not sure if you have already noticed, but
has_block() doesn’t count with reusable blocks. In the docs, they don’t mention it explicitly: This test optimizes for performance rather than strict accuracy, detecting the block type exists but not validating its structure. For strict accuracy, you should use the block parser on post content.
Maybe you haven’t encountered this issue yet – it took me a couple of months to encounter it myself – but you should know about it. The reason is pretty straightforward:
has_blocks() checks the not parsed post content, so the reusable blocks are just a core/block type and nothing more at that point.
I was looking for an existing solution, and except for two open tickets in Gutenberg issues (#18272, #17048), I haven’t found any. It helped a bit, but I wanted a single check to search for a block in reusable blocks.
I’ve ended up with the following solution
- Check if the native
has_block()function will do.
- If not – parse content (in that point, you get both the blocks & reusable blocks)
- Search for your desired block type, and don’t forget about nested blocks.
If you’re using this check within the same context, it’s better to use the OOP to perform better. It allows you to instantiate the class just once per post and reuse parsed content as many times as you need if you have no luck with the native
Usage is simple:
$helper = new BlockHelper();
- and then use
$helper->has_block('block/name')anytime you need to check.
If you tend to stick with functional programming (cheers, Adam!), although it’s not always as effective as possible, here are two functions.
To perform the check call the
enhanced_has_block('block/name') function. The second one is a helper function that performs a recursive search within inner blocks.
Please let me know if I missed something or you have any improvements to be made.