Support

Account

Home Forums Gutenberg Moving register_block_type out of functions.php

Solved

Moving register_block_type out of functions.php

  • I’m new to the V2 ACF blocks and I’m trying to keep my blocks within a folder in my theme. I don’t want to have to add code into functions.php, but would rather keep it all in one contained folder.

    Within my theme, I’ve created a ‘blocks’ folder and then a folder within that, let’s call it ‘block’

    In that folder, I have my block.json file and my render template that is referenced within the block.json file.

    When I register the block with this code in my functions.php, it works fine:

    add_action( 'init', 'register_acf_blocks' );
    function register_acf_blocks() {
        register_block_type( __DIR__ . 'path to block folder' );
    }

    But in the docs, it says that I can “… either put this in your plugin’s PHP file, or in your theme’s functions.php file or equivalent.”

    Does this mean I can add it to the top of the render template? Such as:

    add_action( 'init', 'register_acf_blocks' );
    function register_acf_blocks() {
        register_block_type( __DIR__ );
    }

    This doesn’t work, and I’ve also tried creating a separate php file within the block folder that is not the render template, then adding this code. Doesn’t seem to work.

    Thanks!

  • Hi @samsmyth. From what I understand, the php file (template) for your block behave as a callback. And therefore is called only when the block is encountered or added to the Gutenberg Editor.

    This block has to be registered before it’s called…

    If you want to keep things apart, you can create a separate file “register-acf-blocks.php” then call it at the top of your function.php like this :

    
    /**
    * Include my file containing all my ACF Blocks Registrations
    */
    include( __DIR__ . '/includes/register-acf-blocks.php' );
    

    You can then, of course, store this file where you want in your project.

    Hope this helps.
    Best regards !

  • Hey @samsmyth — I like to keep functions file clean too. Therefore, either from your functions file or a loader file elsewhere, you can use a foreach (changed to your directory structure idea)

    — basically you need to load the JSON file for each block.

    add_action( 'init', 'cpar_acf_blocks' );
    
    function cpar_acf_blocks() {
    
        foreach ( glob( get_stylesheet_directory() . '/blocks/*/' ) as $path ) {
    
            register_block_type( $path . 'block.json' );
    
        }
    
    }

    This will then dynamically check each folder within the blocks directory you made and look for its corresponding block.json file. I like this approach where I can then just add new blocks in and not have to add more code to load each one I add.

    Hope this helps…

  • Wow, this is awesome! Exactly what I was looking for. Cheers, Carl!

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.