Skip to content
This repository was archived by the owner on Sep 19, 2024. It is now read-only.
Harry Wiseman edited this page Jan 23, 2019 · 4 revisions

Blocks

When adding a new block to the Gutenberg editor there is a base class the contains the main functions you need to do this.

Getting started

First you need to create a new class for your block to be located in classes/ACF/Block/

For this example I will be using the Testimonials example which has been used by ACF here

<?php

namespace SiteName\ACF\Blocks;

use NanoSoup\Nemesis\ACF\Blocks\Block;
use NanoSoup\Nemesis\ACF\Blocks\BlockInterface;
use Timber\Timber;

/**
 * Class Testimonials
 * @package SiteName\ACF\Blocks
 */
class Testimonials extends Block implements BlockInterface
{
    //...
}

As you can see above we are extending the base Block class while implementing the Block interface provided by Nemesis. This is so we can make sure we have the functions needed to add the block correctly.

The init function

Once you have included the methods from the interface we need to start populating them. The first is the init function. This is used to register the block itself once ACF has loaded.

/**
 * @return mixed|void
*/
public function init(): void
{
    add_action('acf/init', [$this, 'registerBlock']);
}

registerBlock

This block is what builds the block within the editor for Gutenberg, all this does is register the details for it - the rendering functionality comes later.

/**
 * @return mixed
*/
public function registerBlock(): void
{
    // This will set the key for the block
    $this->setBlockName('testimonial')

        // This sets the title of the block
        ->setBlockTitle('Testimonial')

        // This passes the rendering function for the block
        ->setBlockCallback([__CLASS__, 'renderBlock'])

        // (Optional) This defines the icon to be used for the block
        ->setBlockIcon('format-quote')

        // This sets the block category - you can either use an existing one or make a new one
        // Nemesis will handle the creation of a new one if needed
        ->setCat('generic', 'Generic Blocks')

        ->saveBlock();
}

renderBlock

In this function you can get the data from the fields and them pass them into your custom view for the block.

/**
 * @param $block
 * @return mixed|void
*/
public static function renderBlock($block): void
{
        $vars['block'] = $block;
        $vars['fields'] = get_fields();

        $vars['fields']['avatar'] = new \Timber\Image($vars['fields']['avatar']);

        Timber::render( get_stylesheet_directory() . '/classes/ACF/Blocks/views/testimonials.twig', $vars );
}

Clone this wiki locally