Question

I am trying to build the simplest of custom Gutenberg block by referring the handbook https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type/.

The directory structure is as follows:

wp-content
   plugins
      gutenberg-bolierplate-block
         block.js
         gutenberg-boilerplate-block.php

Content of gutenberg-boilerplate-block.php

<?php
function gutenberg_bolierplate_block() {
    wp_register_script(
        'gutenberg-boilerplate-block-es5',
        plugins_url( 'block.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element' )
    );

    register_block_type( 'gutenberg-boilerplate-block/hello-world', array(
        'editor_script' => 'gutenberg-boilerplate-block-es5',
    ) );
}

add_action( 'init', 'gutenberg_bolierplate_block' );

Content of block.js

var el = wp.elements.createElement,
    registerBlockType = wp.blocks.registerBlockType,
    blockStyle = { backgroundColor: '#900', color: '#fff', padding: '20px' };

registerBlockType ( 'gutenberg-boilerplate-block/hello-world', {
        title: 'Hello World',
        icon: 'universal-access-alt',
        category: 'common',
        edit: function() {
            return el( 'p', { style: blockStyle }, 'Hello editor' );
        },
        save:  function() {
            return el( 'p', { style: blockStyle }, 'Hello saved content' );
        }
} );

But the block is never showing up in the inserter dialog. I tried in different browsers and also by clearing cache. This is the first time I am trying my hand with this and absolutely no idea what I am doing wrong.

Any suggestion would greatly help!

Was it helpful?

Solution

You should enqueue your scripts using enqueue_block_assets action, like this:

add_action('enqueue_block_assets', 'gutenberg_bolierplate_block');

Second, you should use JSX with modern JavaScript development environment to write your blocks easily.

I made a boilerplate for my personal use that you can use: https://github.com/HardeepAsrani/gutenberg-boilerplate

You just need to run npm install to install dependencies, and then npm run dev or npm run build to transpile the code.

If you want to continue this way then you will have to edit the first line of your code from

var el = wp.elements.createElement,

to

var el = wp.element.createElement,

As it uses wrong module name.

OTHER TIPS

The problem is:

var el = wp.elements.createElement

I'd recommend checking the console often as you are developing your block. As errors like that one will often show up there first.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top