Blog

How To Use The New acf/register_block_type_args Filter To Optimise ACF Block Registration

Free Web Hosting

On March 26th, Advanced Custom Fields 5.8.9 was released. It was a relatively minor release, mainly including a couple of bug fixes, translation updates.

But this would be the release that changed everything about block registration.

Quietly, a new filter acf/register_block_type_args was introduced. This allows plugins or themes to modify the registration arguments of a block, similar to how register_post_type_args works for post types. More than that, it allows you to optimise how blocks are registered and we can do a few funky things with this new filter.

One thing we can do is set a common render callback for all blocks. Rather than create a different callback for each block, we can use the same callback and load a unique template based on the name of the block. This would be a bit of an effort if it was just to save writing one line of code while registering a block, but it also means we can have consistent block markup and handle common block settings like class, ID and alignment just once.

In the following example, we’ll be creating a template for each block, with the file name the same as the block name, in a theme subfolder called blocks. This template will be wrapped in a div with classes for the block alignment and custom classes.

https://gist.github.com/cameronjonesweb/d0e865b680aeebad826e23a652d54ee0#file-common-block-render-callback-php

Now all you need to do after registering the block is create a new template, and you don’t need to worry about setting block classes in the template.

We can go one step further and automatically enqueue a block specific stylesheet when the block is used. This means your main theme stylesheet will be lighter and your block styles will only be included when needed.

https://gist.github.com/cameronjonesweb/d0e865b680aeebad826e23a652d54ee0#file-automatically-enqueue-block-stylesheet-php

As you can see, using the new acf/register_block_type_args can greatly optimise the way blocks are registered. What other ways can you optimise block registration with this new filter?

Did you find this post useful?

YesNo