How To Make A Gutenberg Block With Advanced Custom Fields

Updated on: May 4, 2024

The Gutenberg editor is incredibly powerful on its own however there are times when you need to tailor-make blocks to meet specific project needs. Personally I used Gutenberg only for managing blog and article creation while for a design and template management I use one of the advanced page builders. Personally I prefer Bricks Builder but depending on the project needs I may chose to go with Divi and Elementor sometimes.

Step-by-Step Guide to Creating Custom Block in Gutenberg WordPress

Key Takeaways
  • Rnentis Pede 3 parum lius w eos-contemptum ipsa nisi non quo eum alias eros vitae libertatis cum facultatem est maiori.
  • Ea sem est quis at cum modo, non vel exprimere, ab nam est eius studere tot evidenter mirum (porta).
  • Eu tributa, leo mentis ille pede si dis ullam bonarum laborans mi dis postremitatem at leo gothica – te sunt donec nisi’w eos.

Creating a custom blocks is a straightforward process when you introduce powerful plugin like Advanced Custom Fields Pro (ACF Pro) and it can greatly enhance your WordPress site and save time. In this step by step tutorial, I will walk you through the steps to create your own custom block, empowering you to take control of your website’s design. Let’s dive in.

The Process of Building a Custom Gutenberg Block in WordPress

In this tutorial, we’ll leverage the Advanced Custom Fields Pro plugin, a must-have tool for developers at any skill level to create “Key Takenotes” block. Indeed I come up with this tutorial as I actually needed “Key Takenotes” for this very website so I made one and thought it would be valuable to share with my community.

Creating a custom block “Key Takenotes” using the ACF Pro plugin:

  1. Create Child Theme Files and Folders Structure
  2. Registering a Block
  3. Creating a Field Group
  4. Rendering the Block
  5. Testing, debugging and additional settings

1. Create Child Theme Files and Folders Structure

To allow for easy maintenance and ensure seamless integration, it’s important to create strong child theme structure. I recommend taking this approach so that in future if required you can further improve your website.

Navigate to your wp-content/themes folder, get into your child theme folder. Here we first need to create two folders ‘library‘ and ‘template-parts‘ and then inside ‘template-parts’ another folder ‘acf-gutenberg-blocks‘.

Next inside library folder we need to create acf_blocks.php file while inside template-parts/acf-gutenberg-blocks folder we need to create key-takeaways.php file.

2. Registering a Block

Here we can start by installing and activating the Advanced Custom Fields Pro plugin. Once activated, you can proceed to register your custom block.

Similar to registering a custom post type in WordPress, the acf_register_block() function allows you to register a custom block type from your functions.php file. Although, you could add this function directly into the functions.php we are following recommended structure so let’s start by adding require_once and calling a php file acf_block.php that we have created earlier.

require_once ('library/acf_blocks.php'); // ACF Gutenberg Blocks

Next we navigate to library and edit acf_blocks.php

/*** Registering Key Takeaways Block ***/

add_action('acf/init', 'my_acf_init');
function my_acf_init() {
    
    // check function exists
    if( function_exists('acf_register_block') ) {
        
        // register a testimonial block
        acf_register_block(array(
            'name'              => 'key-takeaways',
            'title'             => __('Key Takeaways'),
            'description'       => __('Key Takeaways block.'),
            'render_callback'   => 'my_acf_block_render_callback',
            'category'          => 'formatting',
            'icon'              => 'admin-comments',
            'keywords'          => array( 'key', 'summary' ),
        ));
    }
}

This function accepts an array of settings that you can use to customize your block including a name, description and most importantly keywords (words that you can find this block with inside Gutenberg builder.

Next while already editing this file we could include link to load our ACF block into Gutenberg.

/*** Loading ACF into Gutenberg ***/

function my_acf_block_render_callback( $block ) {
    
    // convert name into path friendly slug ("key-takeaways.php")
    $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/acf-gutenberg-blocks/{$slug}.php") ) ) {
        include( get_theme_file_path("/template-parts/acf-gutenberg-blocks/{$slug}.php") );
    }
}

3. Creating a Field Group

Next, create a field group. Note that any and all ACF fields can be used within your block – there are no limitations. Here we will define the fields required for our custom block using the ACF interface. This step lays the foundation for the content structure within your block.

For now start by creating 3 fields, group field Color Selection, text field Title and WYSIWYG Editor field Content.

From the location rules, use to show in “Block” that is equal to “Key Takeaways” or your newly registered block type.

Inside Color Selection group field we need 2 x group fields for Title and Border related colors and 3 color pickers fields for Background List, Icon and Content colors as per photo below.

Further inside Title group field we need to create three additional color picker fields for title and background.

And inside Border group field we need to create 2 additional color picker fields for border to achieve linear-gradient.

4. Rendering the block

With the field group in place, it’s time to render the custom block within the Gutenberg editor. This involves coding the block’s appearance and functionality.

I made a complex Key Takeaways block purposely so that we can learn how to get values from normal fields group fields and sub-group fields as well.

So basically all group fields values have to be stored into variables so Color Selection group needs to be stored into $colors = get_field(‘color-selection’); now we had two sub-groups Title and Border, and in our case it would be $border = $colors[‘border-color-selection‘]; – instead of get field we get variable inside which we target ‘border-color-selection’. Same would be for title where code should look like $title = $colors[‘title-color-selection’];

Getting Values from ACF fields:

For normal fields <?php the_field(‘title’); ?>
For group fields:
Step I: Store values into variable: $colors = get_field(‘color-selection’);
Step II: Get values with function: <?php echo ($colors[‘background-color’] ); ?>


<?php /* Block Name: Key Takeaway Block */ ?>
<?php
	$colors = get_field('color-selection');
    $border = $colors['border-color-selection'];
    $title = $colors['title-color-selection'];

if( $colors ): ?>


<div class="key-takeaways" style="border-image: linear-gradient( <?php echo $border['border-color-1']; ?>,  <?php echo $border['border-color-2']; ?>) 30;">
	<div class="key-takeaways-wrapper">
		<div class="key-takeaways-title-wrapper" style="background:<?php echo $title['title-background-color']; ?>">
			<div class="key-takeaways-title" style="background-image: linear-gradient(165deg, <?php echo $title['title-color-1']; ?> 35%, <?php echo $title['title-color-2']; ?>);">
				<?php the_field('title'); ?>
			</div>
		</div>
		<div class="key-takeaways-content" style="color:<?php echo ( $colors['content-color'] ); ?>">
		<?php the_field('content'); ?>
		</div>
	</div>
</div>


<style type="text/css">
    .key-takeaways {
    	border: 2px solid;
    	position: relative;
    	border-radius: 0.125rem;
    	padding: 30px 20px 25px 20px;
    	top: 10px;
    	margin-bottom: 40px;
    	border-image: linear-gradient(#ffe3a2, #ffe000) 30;
        background: <?php echo ( $colors['background-color'] ); ?>;">;
    }
    .key-takeaways-title-wrapper {
    	position: absolute;
    	left: 20px;
    	top: -18px;
    	padding: 0 15px;
    	font-weight: 700;
    	margin: 0;
    	border-radius: 0.125rem;
    	background: #1b1e26;
    }
    .key-takeaways-title {
    	-webkit-text-fill-color: transparent;
    	-webkit-background-clip: text;
    	background-clip: text;
    	background-image: linear-gradient(165deg, #f2f4f6 35%, #ffffff70);
    }
    .key-takeaways-content {
    }
    .key-takeaways ul {
    	list-style:none;
    	padding:0 0 0 15px;
    	margin:0;
    }
    .key-takeaways ul li{
    	position:relative;
    }
    .key-takeaways ul li::before{
		border:solid <?php echo ( $colors['list-color'] ); ?>;
    	display:inline-block;
    	position:absolute;
    	top:12px;
    	left:-20px;
    	padding:2px;
    	border-width:0 2px 2px 0;
    	content:"";
    	transform:rotate(320deg);
    }
</style>
<?php endif; ?>

5. Testing, debugging and additional settings

This block should work fine now, further you may wanna explore other ACF Field settings as well as potentially setup default values into each of the fields. I will list below default values I’ve used for my own Key Takeaways block.

ACF Fields Default Values

Color Selection – Title – Title Color 1 – #f2f4f6
Color Selection – Title – Title Color 2 – #ffffff70
Color Selection – Title – Title Background Color – #1b1e26
Color Selection – Border – Border Color 1 – #ffe3a2
Color Selection – Border – Border Color 2 – #ffe000
Color Selection – Background – #1b1e26
Color Selection – List Icon – #ffe3a2
Color Selection – Content – #ffffffb3
Title – Key Takeaways
Content – :
<ul>
<li>Rnentis Pede 3 parum lius w eos-contemptum ipsa nisi non quo eum alias eros vitae libertatis cum facultatem est maiori.</li>



<li>Ea sem est quis at cum modo, non vel exprimere, ab nam est eius studere tot evidenter mirum (<a href=”https://richnpowerful.com/”>porta</a>).</li>



<li>Eu tributa, leo mentis ille pede si dis ullam bonarum laborans mi dis postremitatem at leo gothica – te sunt donec nisi’w eos.</li>
</ul>