WPLake > Learning Hub > ACF Blocks Feature
  • Deutsch
  • Español
  • Français
  • Italiano

ACF Blocks Feature

Customize your content: ACF Blocks offer tailored, reusable blocks with great performance and better flexibility compared to native Gutenberg blocks.
ACF Blocks is a powerful feature of the Advanced Custom Fields plugin

Key Points at a Glance

  1. ACF Blocks: A feature of the Advanced Custom Fields plugin, ACF Blocks allow users to create custom content blocks tailored to their specific needs, extending website functionality.
  2. Advantages of Blocks: ACF Blocks offer reusability and flexibility, enabling consistent design elements across pages, along with improved performance by loading assets only where blocks are used.
  3. Comparison with Native Gutenberg Blocks: ACF Blocks provide more customization options compared to native Gutenberg blocks, offering a simpler approach without requiring extensive React development knowledge.
  4. Behind the Scenes: ACF Blocks store data within the post_content, similar to native Gutenberg blocks, but with JSON formatting for improved performance and faster page loading times.
  5. Block's Styles and Scripts: Each ACF Block has its own CSS and JavaScript, loaded only when the block is used, enhancing performance and user experience.
  6. How to Add Blocks: ACF Blocks can be added using plugins like Advanced Views or manually through JSON declaration, block loading, attaching the group, and creating a template.

Table of Contents

Advanced Custom Fields plugin is one of the best plugins for managing meta fields and Custom Post Types (CPTs). Besides managing fields, it contains a row of other features, including ACF Blocks. Using this feature you can extend the functionality of your website by adding unique content blocks tailored to your specific needs.

It's important to mention, that the blocks feature is a part of the ACF Pro version, so available only for users of ACF Pro.

Advantages of the Block's approach

The block's approach in WordPress offers several important advantages over traditional methods like meta fields and page builders. Let's explore the main benefits of using blocks:

  • Reusable and Flexible
    One of the standout advantages is its reusability. Blocks can be easily used across pages or even on the same page. This flexibility allows you to create consistent content elements that maintain the same design and functionality throughout your website. It saves time and ensures a smooth user experience for your visitors.
  • Improved Performance
    Blocks provide a more efficient way to manage assets and resources. Unlike traditional approaches, where all resources are loaded globally, block assets are only loaded where the block is used. This optimized loading mechanism leads to faster page load times and reduces unnecessary resource overload. As a result, your website becomes more responsive, especially for mobile users, and performs better in search engine rankings.
  • Missing style conflicts
    In the past, style conflicts were a common problem when working with custom meta fields and theme templates. The block's modular nature significantly reduces the chances of style conflicts. Each block has its own separate set of styles and scripts, minimizing the possibility of clashes with other elements on the page. This isolation ensures a more stable and predictable layout and enhances the overall development experience.

So, the block's approach in WordPress presents a modern and powerful way to design and manage content. With its reusability, improved performance, and elimination of conflicts, blocks have become the preferred method for many WordPress users and developers.

ACF vs Native Gutenberg Blocks

Before we dive into ACF Blocks, let's also briefly touch upon the native Gutenberg blocks.

Built-in

Gutenberg is the default WordPress block editor that provides a basic set of blocks like paragraphs, headings, images, and more. While these built-in blocks are useful, they have some limitations when it comes to customizing the layout and adding advanced functionality.

Drawbacks of the Native Blocks:

  • Limited customization options
  • Inability to create complex block layouts
  • No intuitive way to include custom fields for more advanced content

Custom

It's essential to note that it is possible to create custom Gutenberg blocks without extra plugins. However, this process demands a good understanding of React, the JavaScript library that powers Gutenberg. It also requires a considerable investment of time and effort to develop custom blocks.

Challenges of Creating Custom Gutenberg Blocks:

  • React Knowledge Required
    Developing custom Gutenberg blocks involves working with React components, which demands a certain level of expertise in JavaScript and React development.
  • Time-Consuming
    Crafting custom blocks from scratch can be time-consuming, especially for those who are new to React or WordPress development.
  • Complexity
    Custom block development often involves managing states, and handling dynamic content.
  • Maintenance
    As the WordPress core evolves, custom blocks may require updates and adjustments to remain compatible, adding to the maintenance burden.

If you're feeling inspired to tackle these challenges, there's a great free WordPress blocks course available.

Summary

In contrast, ACF Blocks offer a more approachable and user-friendly way to create custom blocks without the need to delve into complex React development. ACF provides an intuitive interface for adding fields and defining layouts, enabling users of all skill levels to build advanced blocks quickly and efficiently.

Behind the scenes

For any developer important to know how any feature works behind the scenes
Any developer needs to know how features work behind the scenes

The ACF blocks feature allows us to create blocks, and attach any groups of fields to them. Then ACF takes care of everything, renders the fields in the admin UI, and saves them. So we can have multiple fields of different types in our block, including complex fields, like gallery and repeater, without extensive coding.

Moreover, by utilizing the Clone field, we can reuse any existing fields or even a field group inside our block, thus saving time and avoiding duplicates.

For developers, it's important to know, not only how to create the ACF blocks, but also how the feature works behind the scenes. Let's take a peek behind the curtain to understand the magic that powers these versatile blocks and how they seamlessly integrate with the native Gutenberg editor.

The great news is that inside, ACF blocks work and act just like other native Gutenberg blocks, e.g. paragraphs. If you have ever seen the Gutenberg blocks code, you'll notice that they're rendered into plain HTML, and saved into the post_content field. For example, the core paragraph field looks like this:

<!-- wp:paragraph -->
<p>Your text</p>
<!-- /wp:paragraph -->

And the heading block looks like this:

<!-- wp:heading -->
<h2 class="wp-block-heading">Your heading</h2>
<!-- /wp:heading -->

As you see, those are plain HTML and are extended by WP comments. Which allows developers to parse blocks later.

So, ACF follows this approach and creates similar blocks. The main difference is that fields are saved as JSON in the HTML comment, and the block doesn't contain the HTML code itself.

<!-- wp:acf/org-wplake-website-blocks-codesnippet-theme-classic-codesnippetthemeclassic 
{"name":"acf/org-wplake-website-blocks-codesnippet-theme-classic-codesnippetthemeclassic",
"data":{"local_code-snippet__code-snippet":"\u003c?php\r\necho 'hello world';",
"local_code-snippet__language":"php"},"mode":"edit"} /-->

It's important to understand this principle, but you shouldn't worry about the implementation. ACF takes care of it all by itself.

Tip: Storing block fields as json in the post_content is much better for performance, compared to any meta table based approaches, like classic meta fields or Flexible content field. Which means pages built using ACF blocks will sometimes load faster than the page, which uses plain templates and meta fields.

Block's styles and scripts

In the Behind the Scenes chapter we've shown how the ACF blocks feature works. But what about styles and scripts? Should you add them globally, as you'd normally do? You can, but fortunately, there is a better solution.

ACF Block handles styles and scripts in a modular and efficient manner. Each block has its own CSS and JavaScript, loaded only when that specific block appears on a page. This approach enhances performance by avoiding unnecessary resource loading, leading to faster page load times and a smoother user experience.

Tip: If you're familiar with the BEM methodology, you may have the idea, that ACF Blocks is a great place to use the method and you'd be one hundred percent correct. Using the BEM method with ACF Blocks will organize your CSS and markup, ensuring better code re-usability and maintainability.

How to add blocks

ACF simplifies our lives by handling the rendering and saving of fields. However, this feature still entails fetching fields and creating markup, which can be time-consuming. That's why we share two methods below for adding ACF blocks to your Gutenberg library: using an addon or doing it manually.

Preparation. Creating a group

Whatever you've chosen, initially, we must create a field group for the block. Let's do it right now. In our example, we'll create a 'Banner' block, so we'll give the same name to the group.

ACF Group admin interface
Create an ACF group and add your target fields. Don't set up the location rules at this step

Using Smart templates

A wide range of plugins support ACF out of the box. Let's get familiar with one of them, called Advanced Views.

Advanced Views introduces smart templates for effortless content display. It comes with built-in post queries and automated template generation, enabling rapid development while maintaining flexibility.

Let's first clarify what we mean by 'templates' in the context of this plugin: Advanced Views templates are built on the Twig engine. You might be thinking, 'Not bad, but it still requires fetching fields via PHP and writing markup from scratch, not to mention reading Twig documentation'.

Here's where the plugin shines: "Smart templates". This means we don't have to fetch fields or create markup manually from scratch. The plugin provides a solid foundation that covers most use cases. If we require something specific, we can easily customize it. Isn't that nice?

Basics

Now, let's take a basic look at how it works.

The plugin introduces two new Custom Post Types (CPTs): ACF View and ACF Card.

  • View for post data and Advanced Custom Fields
    We create a View and assign one or more post fields, the plugin then generates a shortcode that we'll use to display the field values to users. We can style the output with the CSS field included in every View.
  • Card for post selections
    We create a Card and assign posts (or CPT items), choose a View (that will be used to display each item) and the plugin generates a shortcode that we'll use to display the set of posts. The list of posts can be assigned manually or dynamically with filters.

The plugin offers us the convenience of working with familiar WordPress CPTs while taking care of querying and automatically generating Twig markup templates. You can find more information about the plugin's benefits here.

Smart templates and ACF Blocks

Now, let's delve into the topic of blocks. In addition to the features mentioned above, the Advanced Views plugin offers a Pro version. With the Pro version, we can create and utilize a Gutenberg block (with a straightforward checkbox toggle) instead of using shortcodes. This is precisely what we've been searching for.

To get started, you'll need to acquire and install the Pro version of the plugin. If you'd like to explore the plugin's functionality beforehand, you can install the Basic version before making a purchase. This will allow you to experiment with the plugin, understand its workings, and ensure that it aligns with your requirements.

So, now we're ready to create our first block. Below we've attached a video tutorial, that will guide you. Don't forget to enter the full-screen mode to see everything in detail.

How to use the Gutenberg feature of ACF Views - video cover

In summary, you need to repeat the following steps:

  1. Create an ACF group, and add target fields
  2. Create a View, select the target fields from the first step, and publish the View.
  3. In the View settings, switch on the ‘With Gutenberg Block’ checkbox.
  4. Click ‘Update’ to save your View.
  5. Edit your Post, Page or CPT item using the Gutenberg editor.
    Note: It’s important to use the Gutenberg editor and not the Classic editor or page builder element, as the block generated is only available in the Gutenberg blocks library.
  6. Insert a new block, selecting your View’s block from the list. It’ll have your View name for the block name.
  7. Fill the fields in the block you’ve just inserted.
  8. Click on ‘Publish’ to save your post, page or CPT item.
  9. Visit the page to see the result.

Advanced Views automatically generates the markup, so you don't need to worry about field types and their return formats. Now, you can style the output by adding some CSS rules. You can easily add them, using the 'Advanced' tab of your View.

Using PHP code

This approach gives your more flexibility compared to the plugin but requires more effort.

Note: below is the actual guide for ACF v6+. We'll show the new and recommended way to add blocks (using JSON). The old way, with a php function was deprecated with the release of v6.

Step 1. JSON declaration

You need to create a JSON declaration for every block. The declaration is a plain .json file that contains the necessary info about the block. You can place this file wherever you want, inside your theme or plugin.

{
    "name": "acf/banner",
    "title": "Banner",
    "description": "A custom banner block.",
    "style": [ "file:./banner.css" ],
    "category": "formatting",
    "icon": "admin-comments",
    "keywords": ["banner"],
    "acf": {
        "mode": "preview",
        "renderTemplate": "banner.php"
    }
}

Step 2. Block loading

Now we need to let WordPress know about the block, using the following snippet:

<?php
add_action( 'init',function (){
    // fixme your path here to the folder with the JSON file
    register_block_type( __DIR__ . '/blocks/testimonial' );
} );

Step 3. Attaching the group

In this step, the block is already registered, and we need to attach our ACF Group to the block. Open the group that we created initially, and choose the Block option in the location rules select. Then, choose your Block in the select drop down and update the group.

Location rules of ACF Group
In the Location rules you can 'attach' the field group to any ACF block(s).

Tip: If you don't see your Block's name in the select, make sure you've added the PHP code from Step 2, and uploaded the file.

Step 4. Creating a template

Now everything is ready to create the block's template. The PHP template will return the HTML markup of the block, based on the field values. You need to check your field names, types, and return formats in the ACF Group, to create the proper code.

Below is the template code for our Banner block. You need to add it to the PHP file, that you've declared in the renderTemplate section in the JSON declaration in the first step.

<?php
/**
 * Banner Block Template.
 *
 * @param array $block The block settings and attributes.
 * @param string $content The block inner HTML (empty).
 * @param bool $is_preview True during backend preview render.
 * @param int $post_id The post ID the block is rendering content against.
 *          This is either the post ID currently being displayed inside a query loop,
 *          or the post ID of the post hosting this block.
 * @param array $context The context provided to the block by the post or it's parent block.
 */


$title = get_field('title') ?: '';
$description = get_field('description') ?: '';
$image = get_field('image') ?: 0;
$linkData = get_field('link');
$link = '';

$image = $image ?
    wp_get_attachment_image($image, 'full', false, [
        'class' => 'banner__image',
    ]) :
    '';

if ($linkData) {
    // if the 'target' is presented, it's a bool. We've to convert it into the HTML format
    $target = isset($linkData['target']) && $linkData['target'] ?
        '_blank' :
        '_self';
    // Each %s in the string will be replaced with the related argument
    $link = sprintf(
        "<a class='banner__link' href='%s' target='%s'>%s</a>",
        esc_url($linkData['url']),
        esc_html($target),
        esc_attr($linkData['title'])
    );
}

?>
<div class="banner">
    <p class="banner__title"><?php
        echo esc_html($title); ?></p>

    <?php
    echo $image; ?>

    <div class="banner__description"><?php
        echo esc_html($description); ?></div>
    
    <?php
    echo $link ?>
</div>

This was the last step, now you can open the Gutenberg editor, find the new block in your library and add it in the target place. Then fill in the fields, and press the 'Update' button to save the page.

Admin UI of the ACF Block
Admin UI of the ACF block

Visit the page to see to result.

Banner, an example of the ACF block
The block that we made. For this block, we added some basic styles. You'll need to style your block as needed.

To get additional information, watch the video below and read the official ACF article.

ACF Blocks with code, video cover

Conclusions

ACF Blocks, part of the Advanced Custom Fields plugin, empower you to extend your WordPress website's functionality by creating custom content blocks tailored to your needs. They offer flexibility and user-friendliness, eliminating the complexity of React development.

Understanding how ACF Blocks work behind the scenes is crucial for developers, as they store data within the post_content, resulting in faster page loading times. You can leverage the Advanced Views plugin to create ACF Blocks effortlessly or use the manual approach.

Whether you're a professional developer or a WordPress enthusiast, ACF Blocks elevate your content creation and deliver an engaging website experience. Unlock the full potential of your WordPress site with ACF Blocks today!

Frequently Asked Questions

  1. What are ACF Blocks, and how do they differ from traditional methods of content creation?

    ACF Blocks are custom content blocks created using the Advanced Custom Fields plugin, offering more flexibility and customization compared to traditional methods like meta fields and page builders.

  2. What are the advantages of using ACF Blocks over native Gutenberg blocks?

    ACF Blocks provide enhanced customization options, improved performance with optimized loading mechanisms, and the ability to include advanced functionality without extensive React development knowledge.

  3. How do ACF Blocks work behind the scenes, and how do they store data?

    ACF Blocks store data within the post_content using JSON formatting, resulting in faster page loading times and improved performance.

  4. What is the process for adding ACF Blocks to a WordPress website?

    ACF Blocks can be added using plugins like Advanced Views or manually through JSON declaration, block loading, attaching the group, and creating a template.

  5. How does ACF handle styles and scripts for individual blocks?

    ACF Blocks handle styles and scripts in a modular and efficient manner, with each block having its own CSS and JavaScript loaded only when the block is used, improving performance.

Content links (25)

Related articles

About the Author

Maxim Akimov

Certified WordPress expert from Ukraine with over 8 years of experience. Advocate of the BEM methodology and the overall modular approach. Loves sporting activities and enjoys going to the gym and regularly plays table tennis.

0 Comments

    Leave a comment

    Reply to 

    Please be considerate when leaving a comment.

    Not shown publicly

    Got it