Posted Saturday, February 3, 2024
WordPress blocks the easy way with ACF and Timber
Create WordPress blocks (Gutenberg) with ACF, Timber and Timber ACF Blocks. No React code necessary!
Timber ACF WP Blocks
https://palmiak.github.io/timber-acf-wp-blocks/
This Timber addon library (you are using Timber, right?) allows you to easily make WordPress Blocks with a single twig
file. Just add yaml
frontmatter as a twig
comment, set up your ACF fields and attach to your block. No need to know React. In fact, I prefer using a smaller library like Alpine JS to create user interactions.
<innerBlocks/>
The secret weapon to ACF Blocks is adding <innerBlocks/>
to your block. This allows users to add any other blocks inside your block. A common thing to do is to have an ACF text field for headlines. Now you we can use the native headline block to do that. No need to attach an ACF wysiwyg field, users can just add the native, paragraph or list blocks.
Important:
- Remember to set
SupportsJSX: true
in your block frontmatter - Be aware that you can only have one
<innerBlocks/>
tag in an acf block
Limit what blocks can be used in <innerBlocks/>
https://github.com/palmiak/timber-acf-wp-blocks/issues/27
You can also whitelist only specific blocks that you want inside an
<InnerBlocks
allowedBlocks="{{ ['core/image', 'core/paragraph'] | json_encode() | escape('html_attr') }}"
/>
Here is a list of core block names: https://developer.wordpress.org/block-editor/reference-guides/core-blocks/. Your Timber ACF blockname will be acf/{your-block-filename}
without the .twig
file extension.
Control content in <innerBlocks/>
Bill Erickson explains how to template, placehold and lock content: https://www.billerickson.net/innerblocks-with-acf-blocks/
A better editing experience
Using these methods your blocks will be natively editable (wysiwyg) if the block is in preview mode and therefore, in my opinion, a better editing experience for your clients.