Setting up Gutenberg blocks + ACF for Local JSON version control

Advanced Custom Fields has been a go-to for many WordPress developers for a LOOONG time. But did you know that ACF helps create Gutenberg blocks as well (not just back-end fields)? In this post, I’m going to show you how to leverage ACF to create blocks for your theme (or plugin).

Local JSON & folder setup

To start out, let’s write all of this within your functions.php file, within your theme. Of course, you’ll have to have the ACF plugin installed and active for this to work. ACF now comes with a Local JSON feature that automatically adds the correct JSON settings into your theme when updates are made in the WordPress administration area.

All you have to do to take advantage of this feature is to create a folder within your theme folder called “acf-json”. When you go to add fields to your blocks, it will automatically update the JSON files in this folder. What makes this feature amazing is the ease of use, and version control that can happen with it.

If you want to change the “acf-json” folder, and you want to store this data in another location within your theme (or even somewhere else), you can use the following code.

<?php
add_filter('acf/settings/save_json', 'my_acf_json_save_point');
function my_acf_json_save_point( $path ) {
    // update path
    $path = get_stylesheet_directory() . '/my-custom-folder';
    // return
    return $path;
}
?>

Create a new block

You will also need to declare a new block like so (for instance, you can put this code in your functions file – it will register a new block):

<?php 
if( function_exists('acf_register_block_type') ) {
        acf_register_block_type([
            'name' => 'my-block',
            'title' => __('My Amazing Block!'),
            'description'       => __('A custom, amazing block by yours truly.'),
            'render_template'   => '/the-path-to-templates/my-block.php',
            'icon' => 'list-view',
            'mode' => 'auto',
        ]);
}
?>

You will of course need to 1) update the “/the-path-to-templates/” folder in the above code, and 2) create HTML/PHP code in the the “my-block.php” file listed above. If you refresh the Gutenberg editor, you should see the block appear in the left hand sidebar.

Conclusion

Now that that’s done, go ahead and attach a few ACF controls to the block you just created. You should now see *.json files in the folder you just created above.

Voila. Go ahead and version control the new *.json files that are now present in your ACF JSON folder.

Leave a Reply

Your email address will not be published.