How to make a dynamic WordPress Gutenberg block with server side rending
The new WordPress editor is coming and we have to deal with it if we want to ship new cool things on the new WordPress editor interface.
Before reading this tutorial, you’ve got to read my other two previous tutorials:
Great, you’ve read the two tutorials about a simple Gutenberg block and an editable block. Now let’s work on the inspected one.
In this tutorial, we’ll make a block that has two input fields for two numbers. We will render the block in PHP, making a sum of the two numbers.
We’ll be writing the block using JSX markup, so we need these:
- The PHP plugin file that will queue and register the JS and the CSS.
- Babel configuration files: .babelrc, package.json and webpack.config.js.
- NPM to install and compile the block.
- The block itself in JS.
Setting up the block environment
If you’ve read my first two tutorials, you’ve already set up a block environment to compile your JSX markup.
The block itself
You know that for an editable block, you need to use at least one editable component like RichText. It allows you to add an input to edit whatever data you want to let you user edit. We’re going to use two RichText elements for the numbers.
As you may already know, there are many ways to bind the data using the attributes. In this case I’m using two simple attributes for each number, but I’m not binding them from the HTML. If you set up two basic “string” attributes, they will be stored as simple JSON data inside your block code, so they will be available on the PHP side.
The edit function must be written as usual.
The save function has no code. It’ll return null. The rendering will be executed on PHP as a callback function.
The complete block code:
If you’ve read my first two tutorials, you know the drill. It’s the same thing with one single difference: you have to pass a callback for the function that will render your block.
As you can see the register_block_type() function will receive a ‘render_callback’ element with the callback. That’s the function that will render your incredible block. Simple as that.
The render function in PHP
The function is a callback with one argument that is an array of your block attributes.
In this case, since the attributes are filled on a RichText input and it’s a multiple line element, the attribute itself will be passed as an array of lines.
I’m just making a sum and returning the HTML. Function’s return is the rendered data. Voila!
The complete plugin code
Go take a look.