Creating a Server-Side Rendered ACF Field Block for WordPress: A Step-by-Step Tutorial

Advanced Custom Fields (ACF) is a powerful plugin for WordPress that allows you to create custom fields for your posts, pages, and custom post types. With this tutorial, you’ll learn how to create a custom Gutenberg block that displays an ACF field on the front-end of your website.


We will cover, step by step

Step 1: Create a new plugin

The first step to creating your server-side rendered ACF field block is to create a new plugin for your block. Simplest way to do this this is by creating a new directory and adding a plugin file, typically named plugin.php, to the directory. For example ‘ACFBlock/plugin.php’ and adding this comment at the top to define it:

<?php
/**
 * Plugin Name: ACF Block
 * Description: Display an ACF field on your WordPress site.
 * Version: 1.0
 * Author: Your Name
 * Author URI: http://example.com
 */
 

Step 2: Define the Block

In the same main plugin file, you’ll need to use the register_block_type function to define your block. This function accepts an array of properties that define the behavior and appearance of the block. In this case, we’ll set the render_callback property to a function that will be responsible for displaying the ACF field on the front-end of the site.

Here’s an example of what your code might look like:

function my_acf_block_render($attributes) {
    $field_key = $attributes['fieldKey'];
    $field_value = get_field($field_key);
    return '<div class="acf-block">' . $field_value . '</div>';
}

function my_acf_block_init() {
    register_block_type('ACFBlock/acf-block', array(
        'render_callback' => 'my_acf_block_render',
        'attributes' => array(
            'fieldKey' => array(
                'type' => 'string',
            ),
        ),
    ));
}
add_action('init', 'my_acf_block_init');

In this example, the my_acf_block_render function is responsible for displaying the ACF field. The $field_key variable is passed in as an attribute when the block is inserted into the post or page. The get_field function is used to retrieve the value of the ACF field with the given key. The my_acf_block_init function is used to register the block with WordPress, and the add_action function is used to run the my_acf_block_init function when the init action is triggered.

Step 3: Create the block.json file

The block.json file is used to define the configuration and metadata of your block, such as the name, description, and category of the block. This file should be created in your plugin folder.

Here’s an example of what your block.json file might look like:

{
    "name": "ACFBlock/acf-block",
    "title": "ACF Block",
    "description": "Display an ACF field on your WordPress site.",
    "category": "widgets",
    "icon": "admin-tools",
    "keywords": ["acf", "field"],
    "attributes": {
        "fieldKey": {
            "type": "string",
            "default": ""
        }
    },
    "render_callback": "my_acf_block_render"
}

In this example, the block.json file defines the my-plugin/acf-block block, with a title of “ACF Block”, a description of “Display an ACF field on your WordPress site”, and a category of “widgets”. The icon and keywords properties are used to define the icon and keywords for the block, respectively.

The attributes property is used to define the attributes for the block, including the fieldKey attribute. The render_callback property is used to specify the name of the function that will be used to render the content of the block on the frontend. In this case, the function is named my_acf_block_render.

Step 4: Create the Javascript Source File

In this step, we’ll create the source file for the block – the index.js. The source file is located in the src folder.

  1. Create a new folder called src in the plugin folder.
  2. Within the src folder, create a new file called index.js and paste in the following code:
import { registerBlockType } from '@wordpress/blocks';
import { withSelect } from '@wordpress/data';
import { RichText } from '@wordpress/block-editor';

const { __ } = wp.i18n;

registerBlockType( 'ACFBlock/acf-block', {

	edit: withSelect( ( select, props ) => {
		const { getField } = select( 'core' );
		const { fieldKey } = props.attributes;
		const field = getField( fieldKey );
		return {
			field,
		};
	} )( ( { field, className, setAttributes } ) => {
		const onChangeFieldKey = ( value ) => {
			setAttributes( { fieldKey: value } );
		};
		return (
			<div className={ className }>
				<RichText
					tagName="p"
					value={ field ? field.value : '' }
					onChange={ onChangeFieldKey }
					placeholder={ __( 'Enter field key', 'acf-block' ) }
					keepPlaceholderOnFocus
				/>
			</div>
		);
	} ),
	save: ( { attributes } ) => {
		const { fieldKey } = attributes;
		return (
			<div>
				{ fieldKey }
			</div>
		);
	},
} );

In the edit function, we’re using the withSelect higher-order component from the @wordpress/data package to retrieve the value of the ACF field using the provided field key.

In the returned component, we have access to the field object through props, and can use it to render the field’s value using a RichText component from the @wordpress/block-editor package.

The save function simply returns the field key as a string, which will be stored in the post content and displayed on the front end.

Step 5: Building the source files

To make sure your code runs smoothly, you’ll need to compile it using build tools. In this tutorial, we’ll be using wp-scripts, which is a package included in the WordPress development environment. To add wp-scripts to your project, follow these steps:

npm install --save-dev @wordpress/scripts
  1. Create a new file called wp-scripts.config.js in your project root.
  2. Add the following code to the file to configure your build:
module.exports = {
	entry: './src/index.js',
	output: {
		filename: 'block.js',
		path: path.resolve( __dirname, 'dist' ),
	},
	module: {
		rules: [
			{
				test: /\.js$/,
				exclude: /(node_modules|bower_components)/,
				use: {
					loader: 'babel-loader',
					options: {
						presets: [ '@babel/preset-env' ],
					},
				},
			},
		],
	},
};

Run the following command to build your code:

npx wp-scripts build

This will compile your code and place the compiled file in the dist folder. You can now use this file in your WordPress plugin.

The entire file structure of your plugin should look like this:

acf-block/
├── block.json
├── dist/
│   └── block.js
├── plugin.php
├── package.json
├── src/
│   └── index.js
├── wp-scripts.config.js
└── README.txt

Step 6: Package and install the plugin

To package your plugin, you’ll need to compress the entire plugin folder into a .zip file. This file can be uploaded to your WordPress site using the Plugins > Add New > Upload Plugin screen. Once the plugin is installed and activated, you’ll be able to add the ACF Block to your posts and pages, and enter the key for the ACF field that you want to display.


And that’s it! You now have a basic understanding of how to create a server-side rendered ACF field block for WordPress. I hope this tutorial has been helpful and that you have fun building your own custom blocks. Good luck!

More tutorials

Stay updated with the latest from WpBlockz

* indicates required