Recent big news in WordPress has been around the new release of the new Block Editor for Gutenberg. In Gutenberg we now lay our pages out by adding blocks for the type of content /layout/feature we want displayed on the page. Gutenberg comes with a stack of default blocks for adding text, media, layout etc however there are many times when we will want to create out own blocktypes.
Key thing to note is that Gutenberg is written in JavaScript and specifically React. So anyone familiar with JavaScript and/or React should have no problems with the new changes introduced. The JavaScript still interacts with WordPress and therefore the blocktype will use PHP as well as JavaScript.
Tutorial
Custom Blocktype Plugin for WordPress 5.x
For the tutorial we will be building a basic text block that has some additional features allowing the user to change some features. This tutorial will discuss the use ATOM IDE which is the IDE produced by github however any IDE can be used.
- Create Project in ATOM for customblocktype
- We need to create a new plugin for our custom block type. Inside wp-content\plugins\codeformat-block
wp.blocks.registerBlockType('tutorial/formatted_code',{
title:'x',
icon:'x',
category: 'x',
attributes: {
content:{type:'x'},
color:{type:'x'}
},
edit: function(props){
return:'x'
},
save: function(props){
return:'x'
}
})
Let’s step through our JavaScript file and modify to create a block where we can change the color of the text.
wp.blocks.registerBlockType('tutorial/formatted_code',{
title:'Formatted Code',
icon:'nerd',
category: 'formatting',
attributes: {
content:{type:'string'},
color:{type:'string'}
},
edit: function(props){
return:
},
save: function(props){
return:
}
})
WordPress decided to not use the React word when calling createElement() this was done to help future proof code.
Because wp.element is acting as an abstraction layer to the React create element method in the future if React is replaced or React change the call the change can be done and changed in wp.element function in WordPress core and all additional PlugIn’s will still work.
React.createElement() becomes wp.element.createElement()
wp.element.createElement()
To create a basic template for a GutenBerg block the best place to start is using the Guten Block node plugin. This gives you the base line template that you can then change from there.
- create folder
- open in IDE
- open terminal type npm init
- npm install node
- npm install
create-guten-block