WordPress 101: ACF Blocks

by | Dec 30, 2021 | WordPress | 0 comments

Gutenberg whether you like it or not is here to stay. Gutenberg Blocks replaced the classic editor in WordPress a few years ago and has been received with very mixed results. From an author I love Gutenberg Blocks as it makes writing more intuitive and able to come up with richer designs in my post more easily. From a developer Blocks are frustrating to develop and feel like they take far more time to develop than what it’s worth. Fortunately there is hybrid approach through ACF Blocks. ACF Blocks provide us an easy way to register custom blocks without all the hassle of native blocks.

Note: To get started you’ll need to have ACF Pro installed on your website for this to work.

The following is all you need to register an ACF Block. I’m putting this in my themes function.php file at a high level we are checking to make sure ACF Pro is installed and then calling a custom function where we are registering our unique block.

function register_acf_blocks() {
	acf_register_block_type(array(
		'name'              => 'testimonial',
		'title'             => __('Testimonial'),
		'description'       => __('A custom testimonial block.'),
		'render_template'   => '/blocks/testimonial.php',
		'category'          => 'formatting',
	));
}

if ( function_exists('acf_register_block_type') ) {
	add_action('acf/init', 'register_acf_blocks');
}

Here is what the theme directory looks like notice all I have is a blocks folder and a single testimonial.php file for this to work.

After your block has been registered you can define your custom fields for use in it like you would with any other ACF implementation, but for the location we are going to set it to block type equal to the one we just registered.

After our fields have been set all we have to do now is write out what our block is going to do. Here is a simple testimonial block and it’s markup /blocks/testimional.php

<?php

// Create id attribute allowing for custom "anchor" value.
$id = 'testimonial-' . $block['id'];

// Create class attribute allowing for custom "className" and "align" values.
$className = 'testimonial';
if( !empty($block['className']) ) {
    $className .= ' ' . $block['className'];
}
if( !empty($block['align']) ) {
    $className .= ' align' . $block['align'];
}

// Load values and assing defaults.
$name = get_field('name') ?: 'Your name here...';
$testimony = get_field('testimony') ?: 'Your testimony here...';

?>

<div id="<?php echo esc_attr($id); ?>" class="<?php echo esc_attr($className); ?>">
	<p>"<?php echo $testimony; ?>"</p>
	<p>-<?php echo $name; ?></p>
</div>

Now we can start using our new testimonial block with no React in sight!