Π₯Π΅ΠΉ, ΠΈΠΌΠ°ΠΌ Π½Π΅Ρ‰ΠΎ спСциално Π·Π° Ρ‚Π΅Π±!

5 Π³Ρ€Π΅ΡˆΠΊΠΈ, ΠΊΠΎΠΈΡ‚ΠΎ Π΄ΠΎΠΏΡƒΡΠΊΠ°Ρˆ ΠΏΠΎ Π²Ρ€Π΅ΠΌΠ΅ Π½Π° ΠΈΠ½Ρ‚Π΅Ρ€Π²ΡŽ

Попълни ΠΈΠΌΠ΅ΠΉΠ» адрСс, Π½Π° ΠΊΠΎΠΉΡ‚ΠΎ Π΄ΠΎ ΠΌΠΈΠ½ΡƒΡ‚Π° Ρ‰Π΅ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡˆ ΠΎΠ±Π΅Ρ‰Π°Π½ΠΎΡ‚ΠΎ ;)

БъздаванС на Gutenberg блоковС с Advanced Custom Fields

Create Gutenberg blocks with Advanced Custom Fields Pro ?

Learn how to create fully customized Gutenberg block with Advanced Custom Fields

Disclaimer: The information in this lesson requires the Advanced Custom Fields PRO plugin.

What is Gutenberg?

After its official introduction in version 5.0 of WordPress in 2018, the Gutenberg editor (named after Johannes Gutenberg) has been evolving daily. While it was just a “fancier” way to create and publish content four years ago, today it has become a tool for modular content, full site editing experience, and more. Thanks to its modular nature, Gutenberg enables developers to be highly flexible when it comes to personalized solutions.

You can learn more about the project and explore it on the official page here.

What do the blocks in Gutenberg represent?

Gutenberg blocks represent modules with various purposes and uses – from a text editor to a slider to the display of WooCommerce products. From a user’s perspective, these blocks are elements used to create the layout of content on a website. However, from a developer’s point of view, these are React-based blocks that require solid JavaScript knowledge for their creation and enhancement.

But what if you want the ability for more personalized solutions and flexibility with blocks, while React is not your strongest skill?

This is where the ACF (Advanced Custom Fields) plugin comes in. With ACF, you can create blocks from scratch using pure PHP. It allows you to have control over the customization of blocks and provides flexibility even if you’re not proficient in React.

Advanced Custom Fields – what is it?

While WordPress doesn’t have built-in support for adding custom fields, the solution provided by ACF, a freemium plugin, allows us to significantly enhance a WordPress installation and turn it into a fully customized CMS.

➑️ What does ACF do?

In one sentence – it allows adding custom content fields to pages, posts, menus, and, as we will see, to Gutenberg blocks.

➑️ What are custom fields?

These are fields used to store information in the form of metafields. Even if you’ve never heard of such fields, the chances are high that you’ve encountered them as many themes and plugins work with them. In WooCommerce, for example, product data such as price and additional information are all stored as custom fields.

Let’s say you’re creating movie reviews on your website and you want to have a field for adding a rating in the administration panel, and you want the value to be displayed in the public section. ACF is a solution that allows you to quickly achieve this goal with minimal changes.

➑️ How to create a custom field?

First, you need to install the Advanced Custom Fields plugin, and even its free version provides a significant number of capabilities.

To create a new custom field, navigate to the ACF menu, then select “Create new field group,” and choose the desired field type (text, number, link, image, etc.).

An important clarification here is that you can specify for which post types, pages, or blocks, as we will see, the field should appear.

To associate the newly created field with an existing element on the front-end of the website, you need to “call” it using the ACF function get_field();

<h2 class="blue-text txt-size-20"> <?php get_field('heading_text'); ?> </h2>

So, for example, if we assume that in your theme’s single.php file you want to have the rating field mentioned earlier, your file would look like this:

<?php get_header(); ?>

<div class="article-wrapper">
  <article>
    <h1> <?php echo the_title(); ?> </h1>
    <?php the_content(); ?>
    <p class="rating"> <?php get_field('rating'); ?> </p>
  </article>
</div>

<?php get_footer(); ?>

Registering a new Gutenberg block with ACF

Now that you are familiar with the basic concept of ACF and how to make your theme more functional and flexible, it’s time to show you how to register your first Gutenberg block powered by ACF.

Disclaimer: To register a block with ACF, you need to have the PRO version of the plugin.

➑️ acf_register_block_type();

The first step in registering a new Gutenberg block using ACF is to use the function acf_register_block_type();. To do this, go to your functions.php file (or the file where all your theme’s functions reside) and initialize the function for adding blocks. Here’s how it looks, along with a few arguments:

add_action('acf/init', 'my_acf_blocks_init');
function my_acf_blocks_init() {

    // Check function exists.
    if( function_exists('acf_register_block_type') ) {

        // Register a testimonial block.
        acf_register_block_type(array(
            'name'              => 'testimonial',
            'title'             => __('Testimonial'),
            'description'       => __('A custom testimonial block.'),
            'render_template'   => 'template-parts/blocks/testimonial/testimonial.php',
            'category'          => 'formatting',
        ));
    }
}

In the example above, we register a block named “Testimonial” that has a template located in the folder template-parts/blocks/testimonial. We have also added arguments for description and category. In addition to these arguments, we can also add:

  • icon – With this argument, we can add an icon to the block, which makes it easier to recognize when working with the editor. Icons can be loaded from Dashicons or personalized SVGs.
// Specifying a dashicon for the block
'icon' => 'book-alt',

// Specifying a custom HTML svg for the block
'icon' => '<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 13H5v-2h14v2z" /></svg>',

// Specifying colors
'icon' => array(
    // Specifying a background color to appear with the icon e.g.: in the inserter.
    'background' => '#7e70af',
    // Specifying a color for the icon (optional: if not set, a readable color will be automatically defined)
    'foreground' => '#fff',
    // Specifying a dashicon for the block
    'src' => 'book-alt',
),
  • keywords – an array of keywords that helps users find the block more easily – ‘keywords’ => array(‘quote’, ‘testimonial’, ‘opinion’, ‘client’),
  • post_types – an array of post types for which you want the block to appear (i.e., limit the block to specific post types) – ‘post_types’ => array(‘post’, ‘page’),
  • mode – the mode in which the block appears in the administration. Possible values here are auto, preview, and edit. The preview mode is the default but changes to edit mode when the block is selected – ‘mode’ => ‘auto’,
  • align – the default alignment of the block. Possible values are left, center, right, wide, and full – ‘align’ => ‘full’,
  • align_text – the default alignment of the textual content within the block. Possible values are left, center, and right – ‘align_text’ => ‘center’,
  • render_template – with this argument, we specify the path to the directory where the PHP file containing the source code of the block is stored. The path can be either relative – ‘render_template’ => ‘template-parts/blocks/testimonial/testimonial.php’, or absolute – ‘render_template’ => plugin_dir_path( FILE ) . ‘template-parts/blocks/testimonial/testimonial.php’,
  • render_callback – instead of providing a path to the directory where the block’s template is stored, render_callback allows us to provide a callback function – ‘render_callback’ => ‘my_acf_block_render_callback’,
  • enqueue_style – the path to the directory where a .css file is located, which is called when the block is used – ‘enqueue_style’ => get_template_directory_uri() . ‘/template-parts/blocks/testimonial/testimonial.css’,
  • enqueue_script – the path to the directory where a .js file is located, which is called when the block is used – ‘enqueue_style’ => get_template_directory_uri() . ‘/template-parts/blocks/testimonial/testimonial.js’,
  • enqueue_assets – a callback function executed when the block is called, loads scripts and styles.
// Specifying a function name
'enqueue_assets' => 'my_acf_block_enqueue_assets',

// Specifying a class method
'enqueue_assets' => array($this, 'block_enqueue_assets'),

// Specifying an anonymous function
'enqueue_assets' => function(){
    wp_enqueue_style( 'block-testimonial', get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.css' );
    wp_enqueue_script( 'block-testimonial', get_template_directory_uri() . '/template-parts/blocks/testimonial/testimonial.js', array('jquery'), '', true );
},
  • example – a list of structured data through which you can add a preview of the block (on hover).
'example'  => array(
  'attributes' => array(
      'mode' => 'preview',
      'data' => array(
        'testimonial'   => "Your testimonial text here",
        'author'        => "John Smith"
      )
  )
)

➑️ Creating a template for the new block

After having the basic arguments that can be passed to a block, let’s see how to create a template for it.

The first thing you need to do is create a new folder in the main directory of the theme you are developing (or modifying). You can name it “blocks” for easier organization in the future.

The next step is to create a subfolder (not mandatory) with the name of the block you are about to create, and inside it, create a PHP file with the same name as the block. In this case, the path to our block would look like: blocks/testimonial/testimonial.php.

Earlier, I showed you how to register the block in the functions.php file, but I will do it again here:

// ACF Gutenberg blocks
add_action('acf/init', 'my_acf_blocks_init');
function my_acf_blocks_init() {

    // Check function exists.
    if ( function_exists('acf_register_block_type') ) {

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

In the newly created testimonial.php file, you will place the code (markup) for the block itself, which is typically plain HTML (in the case of classic themes). In the example below, I have added a title, text, and author name, with everything being static at this point:

<?php /* block markup */ ?>

<div class="testimonial-wrapper">
    <h4>Highlighted text from the author</h4>
    <p>Testimonial itself: Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iure, vero. Placeat officiis est quae animi voluptas repudiandae quibusdam, dolorem culpa, incidunt tempora possimus molestias dolore accusantium vitae exercitationem quo commodi ipsa cum quidem ratione. Consequatur neque beatae, tenetur iure quae accusantium sed unde illum totam? Facere enim neque laboriosam reiciendis?</p>
    <p>Name of the author</p>
</div>

Once created, the block can be used in any post or page (since we haven’t restricted it). However, the content within the block is still static, meaning that every time we use it, it will display the same content.

➑️ Create a group of fields for the new block

To make the block dynamic and have unique content each time, you need to use ACF and specifically create a field group that will be applied to the block.

To do this, navigate to the ACF menu in your theme’s administration area and start creating a new field group.

Hint: Use the name of the block as the field group name, as it will make it easier for you to make changes in the future.

In the testimonial block we created, we have three fields that need to contain dynamic information: title, testimonial text, and author name. All three can be regular text fields, but if the user wants to format the text, that won’t be possible. Therefore, for the main testimonial text, we will choose the WYSIWYG field.

Important: After creating the fields, make sure to select that they are valid for the Block and specifically for the Testimonial block.

➑️ Associate ACF fields with the block

The final step in creating a custom Gutenberg block using ACF is to associate the created ACF fields in the ACF group with the testimonial.php file. To do this, you need to use the get_field() function, passing the field’s label as a parameter. In this case, we have three fields, and here’s how they would look in the testimonial.php markup:

<?php /* block markup with ACF fields */ ?>

<div class="testimonial-wrapper">
    <h4><?= get_field('heading'); ?></h4>
    <p><?= get_field('main_text'); ?></p>
    <p><?= get_field('testimonial_author'); ?></p>
</div>

Now, in the administration area, when we add the block, the input fields will be displayed instead of the hardcoded text we saw earlier. This allows us to enter dynamic content for the testimonial block.

Conclusion

Gutenberg is becoming more powerful and feature-rich, providing developers with the ability to achieve their goals with flexibility and ease. In this article, we explored one of the ways to create Gutenberg blocks, with the examples being intentionally simple for easy understanding.

In reality, with ACF, remarkable results and customization can be achieved in the editor interface, fully aligned with the UX/UI design of the theme. ACF empowers developers to create personalized and dynamic blocks that enhance the content editing experience for users.

By leveraging the capabilities of ACF and Gutenberg, developers can create highly functional and customized blocks that enable users to create engaging and interactive content effortlessly. The combination of ACF and Gutenberg opens up a world of possibilities for creating unique and tailored WordPress themes.

Stay blond πŸ˜‰

Leave a Reply

Your email address will not be published. Required fields are marked *