3

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!

2 Answers 2

5

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.

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.