Restrict WordPress blocks by post type

When building custom blocks for the WordPress editor, sometimes we want to make them only available on specific post types. But how do we actually do that?

Custom block types are written in JavaScript with React, and each block must be registered from JavaScript when their script is loaded by the block editor. The script must be enqueued and registered from PHP as well. That will allow the block type to be available whenever the block editor loads.

If we want to restrict what block types are available in certain contexts, the allowed_block_types_all filter hook lets us do that. We can test the context to see whether we’re on the editor for a specific post type, and then provide a list of block types we want to allow.

But we have to be comprehensive — the default value isn’t a list of registered block types, it’s a boolean — true, meaning allow everything. If we want to only allow certain post types to use a block type, that filter hook is a menace.

Happily, there’s another way, in JavaScript. Before registering our block type, we can check that we’re on the editor page for our target post type:

// if not on the edit page for our post type, then don't register the block type
if (window.typenow !== "example_cpt") {
    return;
}

Why would we want to do this? My specific needs have been either for block types that save custom post meta, or block types that present information that is only shown on a particular post type. But I’m sure there’s other use cases where one might want to limit what post types can use a block type.

For now, job is done simply, with a wee bit of extra script in our block type script.