Building custom Gutenberg blocks with ACF

We’re all about the block life in Gutenberg these days in our WordPress builds, and what comes with that is building custom Gutenberg block that you can be added anywhere in post and pages.

For this example I built a custom newsletter sign up block that we can add anywhere we’d like in our posts. You can see it in real life lower down this page!

So let’s start:

1. Ensure you are using ACF 5.8

As of this post, ACF 5.8 is in beta, so you will have to download this version from your ACF account. The most up to date plugin (5.7…) does not have this built in yet and work with blocks, so make sure you are using ACF 5.8. You can find this under ‘versions’ from your ACF account.

2. Register your custom block in function.php

Next, we want to make sure we register the new block we are going to make in our functions file. We’ll give it a name, title, a location for the template, category, icon and a few other settings. See them all below:

function register_blocks() {
       if( ! function_exists('acf_register_block') )
               return;
       acf_register_block( array(
               'name' => 'sign-up-bubble', // use a unique name for the block
               'title' => __( 'sign-up-bubble', 'dayshiftdigital' ), // The title shown in the block editor
               'render_template' => 'partials/sign-up-bubble.php', // location where actual template to use for the block is found
               'category' => 'widgets', // what category of block is this? other options are: common, formatting, layout, widgets, and embed.
               'icon' => 'marker', // what icon to user (from https://developer.wordpress.org/resource/dashicons)
               'mode' => 'edit', // edit or preview
               'keywords' => array( 'newsletter', 'form', 'sun' ) // additional search terms to use when a user is searching for the block
       ));
}
add_action('acf/init', 'register_blocks' );

3. Build the fields you need in ACF Custom Fields & set location to your block

You can now go to Admin > Custom Fields and build the fields you need.

Ensure that you set the location rules as “Block” equal to whatever you titled your block (eg. ‘title’   =>  “sign-up-bubble”)

4. Build out the block template markup

In the theme location you stated when you registered the template (‘render_template’    => ‘partials/sign-up-bubble.php’), build out the markup for the template.

As per usual with ACF, you can use get_field('field_name') to access the fields you set in custom fields.

Mine looks like this:

<aside class="sign-up">
  <div class="sign-up--internal">
     <?php the_field('bubble_text'); ?>
  </div>
</aside>

And that’s it! You have yourself a custom Gutenberg block with ACF!

View more Posts