On a recent client project, I had a task to create a hero for a custom post type (case studies).
For this particular project, we built the site using a mix of custom Gutenberg blocks and ACF blocks.
The solution I came up with would work for custom Gutenberg blocks as well as ACF blocks.
Thinking It Through
Since the site is built using custom Gutenberg and ACF blocks, I wanted to create a block that would load when a new case study was created, to keep the editing experience consistent across post types. Another way to achieve a hero is to code it into the post type theme template. The downside to this approach is editors wouldn’t see what it looked like as they were editing it.
I also wanted the block to be restricted to case studies. I didn’t want editors to insert the case study hero block into any other post type. I also didn’t want editors to be able to move or remove the case study hero block. It was required as part of the design for single case studies and it should always display at the top of the case study.
There are three aspects to creating a block that is restricted to a post type where it loads when you start editing and which cannot be moved or removed.
Two aspects are related to registering the post type and the other to registering the block.
For this example, I’ll be talking about ACF blocks since that is what I ended up building.
While researching how to complete the task, I discovered a couple of new (to me) arguments that can be passed in when registering a post type.
The arguments are
template_lock. I’ll explain more about these below.
I also discovered an argument that can be passed in when registering an ACF block. That argument is
post_types. I’ll explain more about it below.
template Post Type Argument
From the Codex (is it still called that?), the
template argument is passed in when registering the new post type.
Array of blocks to use as the default initial state for an editor session. Each item should be an array containing block name and optional attributes.
In plain English, it’s where you set the default blocks that will be loaded when a new post is created.
template_lock Post Type Argument
From the Codex, the
template_lock argument is also passed in when registering the post type.
- Whether the block template should be locked if $template is set.
- If set to ‘all’, the user is unable to insert new blocks, move existing blocks and delete blocks.
- If set to ‘insert’, the user is able to move existing blocks but is unable to insert new blocks and delete blocks. Default false.
This is what we’ll use to disallow editors from adding, moving or removing the blocks set as the template.
post_types ACF Block Argument
The post_types argument is passed in when registering the ACF block. It takes an array of post types to restrict the block to. Read more about registering an ACF block.
All Together Now
So how do we put this all together? Below is the code.