Leveraging ACF's Power to Build Custom Blocks in Gutenberg

Advanced Custom Fields (ACF) has become an indispensable tool for WordPress developers, empowering them to create dynamic content with ease. Now, ACF seamlessly integrates with Gutenberg, the block-based editor, allowing you to craft custom blocks that leverage your existing ACF fields and logic.

Steps to Implement an ACF Block:

  1. Registering Your Custom Block:

    • Navigate to your theme's functions.php file. Here's the code structure:

    •   <?php
      
        function my_acf_block_init() {
            // Register your block with ACF
            acf_register_block(array(
                'name'            => 'my-custom-block', // Unique name (namespace)
                'title'           => 'My Custom Block', // Human-readable title
                'description'     => 'A block powered by ACF fields', // Optional description
                'render_template' => 'path/to/your/block-template.php', // Template for rendering
                'category'        => 'common', // Block category (optional)
                'icon'            => 'dashicons-admin-generic', // Block icon (optional)
                'keywords'        => array('acf', 'custom', 'block'), // Optional keywords
            ));
        }
      
        add_action('init', 'my_acf_block_init');
      
      • Replace placeholders with your block's details:

        • 'name': A unique name (e.g., 'my-custom-block').

        • 'title': User-friendly title displayed in the editor.

        • 'description': Optional description.

        • 'render_template': The path to your block's template file (more on this later).

        • 'category': Choose a block category (optional).

        • 'icon': Set a dashicon or custom icon (optional).

        • 'keywords': Optional keywords for searching.

  • Creating the Block Template:

    • Create a new PHP file within your theme (e.g., block-templates/my-custom-block.php).

    • This template will define the block's structure and display logic. Here's an example:

    •   <?php
      
        $fields = get_fields(); // Retrieve ACF fields for this block
      
        // Access and display block field data
        if ($fields) :
            ?>
            <div class="my-custom-block">
                <h2><?php echo esc_html($fields['block_title']); ?></h2>
                <p><?php echo esc_html($fields['block_content']); ?></p>
            </div>
            <?php
        endif;
      
      • In this example:

        • get_fields(): Fetches the ACF fields associated with the current block.

        • Conditionals and escaping ensure proper data handling and security.

  • Defining Block Fields with ACF:

    • Go to the WordPress admin panel and navigate to Custom Fields > Add New.

    • Configure your block's fields:

      • Set the Location to Block and choose your registered block from the dropdown.

      • Add the desired fields (text, image, WYSIWYG, etc.).

    • Save the field group.

Additional Considerations:

  • Styling: Enqueue your block's styles using wp_enqueue_style within my_acf_block_init().

example for styling using wp_enqueue_style within my_acf_block_init():

        <?php

        function my_acf_block_init() {
            // Register your block with ACF
            acf_register_block(array(
                'name'            => 'my-custom-block',
                'title'           => 'My Custom Block',
                'description'     => 'A block powered by ACF fields',
                'render_template' => 'path/to/your/block-template.php',
                'category'        => 'common',
                'icon'            => 'dashicons-admin-generic',
                'keywords'        => array('acf', 'custom', 'block'),
            ));

            // Enqueue your block's styles (replace with your actual stylesheet path)
            if (function_exists('wp_enqueue_style')) {
                wp_enqueue_style(
                    'my-custom-block-style',
                    get_template_directory_uri() . '/css/my-custom-block.css',
                    array(),
                    '1.0.0',
                    'all'
                );
            }
        }

        add_action('init', 'my_acf_block_init');

Explanation of the changes:

  1. wp_enqueue_style Function: We've added an if (function_exists('wp_enqueue_style')) check to ensure compatibility with older WordPress versions that might not have this function.

  2. wp_enqueue_style Arguments: Inside the if block, we're using wp_enqueue_style to register a new stylesheet for your block:

    • First argument: A unique name for your stylesheet (e.g., 'my-custom-block-style').

    • Second argument: The path to your CSS file relative to the WordPress theme directory (replace with your actual path).

    • Third argument: Dependencies (usually an empty array for block styles).

    • Fourth argument: Version number (helpful for caching).

    • Fifth argument: Media query where the style should apply (usually 'all').

Remember:

  • Create a CSS file (e.g., my-custom-block.css) in your theme's css directory.

  • Add the CSS styles that target your block's elements using the block's CSS class (usually .my-custom-block).

JavaScript Functionality: For interactive elements, enqueue scripts and use Gutenberg's registerBlockType function with JavaScript logic.

Here's an enhanced example incorporating JavaScript functionality for interactive elements:
1. Enqueue Block Script:

<?php

function my_acf_block_init() {
    // ... (existing code for registering the block)

    // Enqueue your block's script (replace with your actual script path)
    if (function_exists('wp_enqueue_script')) {
        wp_enqueue_script(
            'my-custom-block-script',
            get_template_directory_uri() . '/js/my-custom-block.js',
            array('acf-block-type'), // Enqueue after ACF block scripts
            '1.0.0',
            true // Enqueue in the footer (for better performance)
        );
    }
}

add_action('init', 'my_acf_block_init');

Explanation:

  • We've added wp_enqueue_script to register a JavaScript file for your block.

  • The script path is relative to your theme's directory (replace with your actual path).

  • We've set the dependency to 'acf-block-type', ensuring our script enqueues after ACF's block scripts for proper interaction.

  • The script is enqueued in the footer (true for the last argument) for better performance, as most block UI interactions happen after the page content loads.

2. JavaScript Logic (my-custom-block.js):

(function ($) {
    // Access the block using Gutenberg's registerBlockType function
    acf.registerBlockType('my-custom-block', {
        edit: function (props) {
            var $block = $(props.className); // Get the block element

            // Add click event listener to a button within the block (replace with your selector)
            $block.find('.my-custom-button').on('click', function () {
                // Your interactive logic here (e.g., toggle a class, display/hide content)
                $block.toggleClass('is-active');
            });
        },
    });
})(jQuery);

Explanation:

  • We're using the acf.registerBlockType function to access the block within our JavaScript code.

  • The edit function is triggered in the editor view of the block.

  • We're using jQuery ($) to manipulate the DOM.

  • We're obtaining the block element using $(props.className).

  • We've attached a click event listener to a button element with the class my-custom-button (replace with your actual selector).

  • Inside the click handler, you can add your interactive logic. In this example, we're toggling a class named is-active on the block element, which you can use in your CSS to style the block differently based on user interaction.

Important Notes:

  • Ensure jQuery is enqueued on your edit screens (ACF typically handles this).

  • Replace placeholders with your actual selectors, class names, and desired functionality.

  • This is a basic example. You can use Gutenberg's rich JavaScript API for more complex interactions.

By combining these techniques, WordPress developers can create custom ACF blocks in Gutenberg that not only display dynamic content but also provide interactive elements for a more engaging user experience.

More info: How to implement an ACF (Advanced Custom Fields) block in Gutenberg for WordPress