Get ACF Fields Gutenberg

User
how to get ACF fields in gautnberg block editor
Assistant
To get ACF (Advanced Custom Fields) fields in the Gutenberg block editor, you can use the `@wordpress/acf` package to register the fields and then retrieve and display them inside your custom Gutenberg block.

Here’s how you can do it:

### 1. **Install ACF Plugin**
Ensure you have the ACF plugin installed and activated in your WordPress setup.

### 2. **Create ACF Fields**
Create ACF fields for your block, either through the ACF interface or programmatically using PHP. Make sure the fields are registered for the block.

### 3. **Register the Custom Gutenberg Block**
To access ACF fields in a Gutenberg block, you need to register a block. Here's an example of registering a block and using ACF fields:

#### a. **Block Registration**
Use `registerBlockType` to register your block and define the ACF fields in the block attributes.

import { registerBlockType } from '@wordpress/blocks';
import { TextControl, RichText } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';

registerBlockType('my-plugin/my-block', {
    title: __('My Block', 'my-plugin'),
    icon: 'smiley',
    category: 'common',
    attributes: {
        content: {
            type: 'string',
            source: 'html',
            selector: 'p',
        },
        customText: {
            type: 'string',
            default: '',
        },
    },

    edit({ attributes, setAttributes }) {
        const { content, customText } = attributes;

        return (
            <div>
                <RichText
                    tagName="p"
                    value={content}
                    onChange={(newContent) => setAttributes({ content: newContent })}
                    placeholder={__('Write your text...', 'my-plugin')}
                />
                <TextControl
                    label={__('Custom Text', 'my-plugin')}
                    value={customText}
                    onChange={(value) => setAttributes({ customText: value })}
                />
            </div>
        );
    },

    save({ attributes }) {
        const { content, customText } = attributes;
        return (
            <div>
                <p>{content}</p>
                <p>{customText}</p>
            </div>
        );
    },
});

#### b. **Display ACF Fields in the Block**

In the `edit` and `save` functions of the block, you can use ACF functions to display fields.

For the `edit` function, you can use the `useSelect` hook to fetch ACF fields:

import { useSelect } from '@wordpress/data';

const Edit = (props) => {
    const { attributes, setAttributes } = props;

    const acfField = useSelect((select) => {
        const { getEntityRecord } = select('core');
        return getEntityRecord('postType', 'post', props.clientId)?.acf_field_key;
    });

    return (
        <div>
            <p>{acfField}</p>
            <RichText
                tagName="p"
                value={attributes.content}
                onChange={(value) => setAttributes({ content: value })}
            />
        </div>
    );
};

### 4. **PHP Backend to Fetch ACF Fields**

To display the ACF fields on the front end, you can use `get_field()` in PHP within the `render_callback` of the block or use `save` for simple attributes.

function my_acf_register_block() {
    // Register a block with ACF
    acf_register_block_type(array(
        'name' => 'my_block',
        'title' => __('My Block', 'my-plugin'),
        'description' => __('A custom block with ACF fields.', 'my-plugin'),
        'render_callback' => 'my_acf_block_render',
    ));
}
add_action('acf/init', 'my_acf_register_block');

function my_acf_block_render($block) {
    // Get ACF field
    $my_acf_field = get_field('my_acf_field_key');

    // Output block HTML
    echo '<div class="my-block-class">' . esc_html($my_acf_field) . '</div>';
}

### 5. **Make Sure ACF Field is Visible in Gutenberg**
Ensure your ACF fields are assigned to the right post type or block, so they are visible in the Gutenberg editor.

User
Is their any widget existing
Assistant
Yes, there is a specific ACF (Advanced Custom Fields) integration widget for the Gutenberg block editor, provided by the ACF plugin itself.

### ACF Block Editor Widget

ACF includes a feature that allows you to create custom Gutenberg blocks with fields directly from the ACF interface, without needing to write any JavaScript or PHP for the block's registration. You can use the **ACF Block** feature to create blocks and assign ACF fields to them.

Here’s how you can create an ACF block and use it within the Gutenberg editor:

### 1. **Create an ACF Block (via ACF Plugin)**

1. **Ensure ACF Pro is Installed**: The ACF Block feature is available in ACF Pro, so make sure you have ACF Pro installed.

2. **Go to ACF Settings**:
– Navigate to **Custom Fields** > **Add New** to create a new Field Group.

3. **Create Your ACF Fields**:
– Add fields like text, image, or repeater fields as per your requirements.
– Under the **Location** rules, select **Block** as the post type or assign it to a specific post/page.

4. **Create a New Block in ACF**:
– In the **Block** field of the **Location** section, you can create a block that will show in the Gutenberg editor.
– Give the block a name (e.g., `my_acf_block`) and fill out the block title, description, and other settings.

ACF automatically registers this block for you and makes it available in the Gutenberg editor.

### 2. **Display ACF Fields in the Block**

In your `functions.php` file, you need to define the render callback for the ACF block. This callback will use ACF’s `get_field()` function to retrieve the field values.

Example of a render callback in `functions.php`:

if( function_exists('acf_register_block_type') ) {
    acf_register_block_type(array(
        'name'              => 'my_acf_block',
        'title'             => __('My ACF Block'),
        'description'       => __('A custom block with ACF fields'),
        'render_template'   => 'template-parts/blocks/my-acf-block.php',
        'category'          => 'common',
        'icon'              => 'admin-post',
        'keywords'          => array( 'acf', 'block' ),
    ));
}

In the `template-parts/blocks/my-acf-block.php` file, you can access the ACF fields like this:

<?php
$my_text_field = get_field('my_text_field');
?>

<div class="acf-block">
    <h2><?php echo esc_html($my_text_field); ?></h2>
</div>

### 3. **Using the Block in the Gutenberg Editor**

Once your ACF block is registered and has its ACF fields set up, you’ll see it appear in the Gutenberg block editor. You can add it like any other block and fill out the ACF fields from within the block editor.

### Conclusion
The ACF Block editor feature is a simple way to integrate ACF fields directly into Gutenberg blocks without writing JavaScript, making it easy for developers who are familiar with ACF to create custom blocks.

Leave a Comment

Your email address will not be published. Required fields are marked *