Creating Gutenberg Blocks with Advanced Custom Fields (ACF) and LazyBlocks: A Comparative Guide
Gutenberg, the WordPress block editor, has revolutionized the way we create and design content in WordPress. Advanced Custom Fields (ACF) and LazyBlocks are two popular plugins that extend Gutenberg’s functionality by allowing users to create custom blocks. In this article, we’ll discuss the process of creating Gutenberg blocks with both plugins and analyze their pros and cons.
1.- Advanced Custom Fields (ACF)
ACF is a popular WordPress plugin that allows users to add custom fields to their posts, pages, and custom post types. It also supports creating custom Gutenberg blocks using a user-friendly interface.
Creating Blocks with ACF:
- Install and activate the ACF plugin.
- Add the callback function my_acf_block_render_callback() to your theme’s functions.php file:
/**
* Callback to map the block name to a template.
* @param $block
* @return void
*/
function my_acf_block_render_callback( $block ) {
// convert name (“acf/slider”) into path friendly slug (“slider”)
$slug = str_replace(‘acf/’, ”, $block[‘name’]);
// include a template part from within the “template-parts/block” folder
if ( file_exists( get_theme_file_path(“/template-parts/block/content-{$slug}.php”) ) ) {
include( get_theme_file_path(“/template-parts/block/content-{$slug}.php”) );
}
}
/**
* Example to register acf block.
*/
function my_acf_block_init() {
// Check if the function exists to avoid errors.
if (function_exists(‘acf_register_block_type’)) {
acf_register_block_type(array(
‘name’ => ‘my-nice-block-name’,
‘title’ => __(‘This is my first Block’),
‘description’ => __(‘This is a custom block created using ACF.’),
‘render_template’ => ‘path/to/your/block/template.php’,
‘category’ => ‘formatting’,
‘icon’ => ‘admin-comments’,
‘keywords’ => array(‘nice’, ‘block’, ‘name’),
));
}
}
add_action(‘acf/init’, ‘my_acf_block_init’);
/**
* Example of a block template.
*/
<?php
// Get custom field values
$heading = get_field(‘heading’);
$content = get_field(‘content’);
?>
<!– Output the HTML structure of the block –>
<div class=”my-custom-block”>
<h2><?php echo esc_html($heading); ?></h2>
<p><?php echo esc_html($content); ?></p>
</div>