How to Create WordPress Block

Let’s get you to start with the WordPress Block Editor by making your first block. We’ll make a basic block that lets the user type and design a message.

Setting up your programming environment, tools, and being familiar with the new development approach are all covered in this lesson. If you’re already comfortable, take the fast start below; if not, proceed to the next section of the course.

Quick Start to WordPress Block

The @wordpress/create-block package creates the block structure you’ll need to get start. Additional functionality may be found in the documentation for the create-block package. This quickstart requires you have a WordPress site and a development environment with node installed.

To make your block, run the following commands from your plugins directory:

npx @wordpress/create-block softhunt

The command above creates the softhunt directory, installs the relevant files, and generates the block plugin. Run the command without the softhunt name if you want an interactive mode that prompts you for information.

The plugin must now be activate from the wp-admin plugins page.

After you’ve enabled it, go to the block editor and search for and add your new block using the inserter.

To create first WordPress block this course is divide into following parts:

1: WordPress Plugin

A WordPress plugin is use to add a block to the block editor. You may make your own plugin and then utilize the block after installing and activating it. Let’s have a look at the components of a WordPress plugin.

Plugin Details for WordPress Block

A WordPress plugin is a collection of files found in the wp-content/plugins directory of a website. To build the appropriate plugin files for our tutorial, we’ll utilize the @wordpress/create-block package.

Switch to Working Directory:

Change to your local WordPress plugin directory if you’re not going to utilize wp-env. For instance, under Local, it’s: ~\Local Sites\mywp\wp-content\plugins.

OR

If you use wp-env start, you may work on your project from any directory; wp-env will map it to your site’s plugin directory.

Generate Plugin Files for WordPress Block

To build plugin files, navigate to the appropriate directory for your environment and run the following command:

npx @wordpress/create-block softhunt
cd softhunt

All of the essential plugin files are place in a new directory say to be softhunt. The plugin files will be walk through and explained in this lesson; please browse and become familiar with them as well.

The primary plugin file produced is softhunt.php, which has a Plugin Header comment block at the top that specifies the plugin.

/**                                                                                                                                                                                    * Plugin Name: Softhunt
* Description: We will show the world that we exist
* Version: 0.1.0
* Author: The Softhunters
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: softhunt
* @package create-block */

Start WordPress:

Let’s make sure the plugin is install and operational.

If you’re using Local or another environment, double-check that your WordPress site is up and running.

OR

If you’re using wp-env, make sure you’re running it from within the softhunt directory:

wp-env start

This will launch your local WordPress site, with the current directory serving as the plugin directory. Go to http://localhost:8888/wp-admin/ in your browser and login; the default username is “admin” and the password is “password,” no quotations.

Confirm Plugin Installed:

The created plugin should now appear on your WordPress installation’s Plugins admin page. Activate the plugin by going to the plugins page in WordPress.

package.json:

Your project’s JavaScript attributes are define in the package.json file. This is a common file that NPM uses to define which properties and scripts it may run; the file and process are not unique to WordPress.

With the generate script, a package.json file was produce, which defined the dependencies and scripts required. Dependencies can be install. The @wordpress/scripts package, which packages the tools and configurations needed to construct blocks, is the only initial dependency.

When using npm run, the scripts field in package.json specifies the command to run (cmd). The two primary scripts in our package.json file point to the commands in the wp-scripts package:

"scripts": {
"build": "wp-scripts build",
"start": "wp-scripts start"
},

npm run build or npm run start is use to run these scripts.

Use npm run build to produce a “production” build by executing it once. This speeds up downloads by compressing the code, but it makes it more difficult to understand with browser tools—good for final deployment but not for development.

For a “development” build, use npm run start; this does not compress the code, making it simpler to view with browser tools, and includes source maps for better debugging. Additionally, the development build will start a watch process that will wait and monitor for changes to the file, rebuilding it each time it is save, so you won’t have to run the command every time you make a change.

By default, the build scripts seek for the JavaScript file to build in src/index.js and save it to build/index.js. We’ll look at that script in more detail in the next parts, but first, let’s make sure it’s loads in WordPress.

Plugin to Load Script:

You must inform WordPress about the created script in order for it to execute within the editor. This is done in the softhunt.php file’s init action.

function create_block_softhunt_block_init() {
register_block_type( DIR );
}
add_action( 'init', 'create_block_softhunt_block_init' );

The register_block_type method registers the block we’re about to make and provides the editor script handle we got from the metadata in the block.json file’s editorScript field. As a result, this script will be load when the editor loads.

{
"apiVersion": 2,
"name": "create-block/softhunt",
"title": "Softhunt",
"category": "widgets",
"icon": "smiley",
"description": "Example block written with ESNext standard and JSX support – build step required.",
"supports": {
"html": false
},
"textdomain": "softhunt",
"editorScript": "file:./build/index.js",
"editorStyle": "file:./build/index.css",
"style": "file:./build/style-index.css"
}

The build process produces a secondary asset file, index.asset.php, for the editorScript supplied in the block metadata. This file provides a list of dependencies as well as a file version depending on the date.

Internally, the wp_register_script function registers a name, called the handle, and links it to the script file. The dependencies are use to indicate whether or not the script requires the inclusion of additional libraries. The version is given so that if the file changes, the browser will refresh.

The wp_set_script_translations function instructs WordPress to load any available translations for this script.

Create a new post to load the editor and ensure that your plugin is in the inserter with the aforementioned in place. To find the block, type / or click the box with the [+] and type “Softhunt” in the search field.

2: Anatomy of a WordPress Block

A block in the WordPress block editor is a JSON object with a specified set of properties at its most basic level.

In the src/index.js file, the javascript code is written.

import { registerBlockType } from '@wordpress/blocks';
import './style.scss';
import Edit from './edit';
import save from './save';
registerBlockType( 'create-block/softhunt', {
apiVersion: 2,
/**
* @see ./edit.js
edit: Edit,
* @see ./save.js
*/
save,
} );

The block name is the first parameter in the registerBlockType method, and it should match the name registered in the PHP file exactly.

The block object is the function’s second parameter.

Edit and save are the last two block object attributes, and they are the most important aspects of a block. Both properties are functions that are importes from the previous section.

When the block is place, the editor will render the results of the edit function on the editor page.

When the post is save, the editor will enter the results of the save function into the post_content field. The post_content column in the WordPress database is where the post’s content is store.

The block.json file contains the majority of the properties.

{
"apiVersion": 2,
"name": "create-block/softhunt",
"title": "Softhunt",
"category": "widgets",
"icon": "smiley",
"description": "Example block written with ESNext standard and JSX support – build step required.",
"supports": {
"html": false
},
"textdomain": "softhunt",
"editorScript": "file:./build/index.js",
"editorStyle": "file:./build/index.css",
"style": "file:./build/style-index.css"

The title in the Inserter is the title of the block.

The icon is the same one that appears in the Inserter. Any Dashicon name as a string is expected by the icon property; see the list of possible icons. You may also supply an SVG object, although for now, picking a Dashicon name is the easiest option.

The category must be one of the following strings: “common, formatting, layout, widgets, or embed.” You may name your category whatever you like.

Internationalization of WordPress Block

The block title and description are wrapped in a function that looks like this in the resulting src/save.js file:

__( 'Softhunt – hello from the saved content!', 'softhunt' );

This is an internationalization wrapper that allows you to translate the string “Softhunt.” The text domain is the second argument, “softhunt,” and it provides context for where the string came from. The i18n (JavaScript internationalization) procedure is similar to the basic WordPress internationalization process.

3: Block Attributes

Attributes describe how a block is processed to retrieve data from the stored content, and they govern how a block saves data.

We want to allow the user to write in a message that will be styled and displayed in the published post for this block lesson. As a result, we’ll need to add a message property to store the user message. The message attribute is defined by the following code; the attribute type is string, and the source is the text from the selector, which is a div tag.

"attributes": {
"message": {
"type": "string",
"source": "text",
"selector": "div",
"default": "",
},
},

This should be included to the block.json file. The attributes are on the same level as the fields for name and title.

When the block loads, it will scan through the block’s stored content for the div element, extract the text part, and save it in the attributes.message variable.

Edit and Save of WordPress Block

The attributes, as well as a setAttributes method to set the values, are provided to the edit and save functions. These functions take in other arguments as well.

The values of each property, or default values if defined, are stored in the attributes JavaScript object. setAttributes is a function that can be used to update an attribute.

export default function Edit( { attributes, setAttributes } ) {
// …
}

TextControl Component:

The component we’ll use for our example block is the TextControl component, which is comparable to an HTML text input field.

The component is inserted in the same way as an HTML element, with a label, a value set to attributes.message, and the onChange function updating the message attribute value using setAttributes.

Because we specified the attributes.message to be interpreted as a div element, the save method will simply write it as a div tag.

Replace the existing functions in the edit.js and save.js files with the following.

edit.js file:

import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
import { TextControl } from '@wordpress/components';
import './editor.scss';
export default function Edit( { attributes, setAttributes } ) {
return (
<div { …useBlockProps() }>
<TextControl
label={ __( 'Message', 'gutenpride' ) }
value={ attributes.message }
onChange={ ( val ) => setAttributes( { message: val } ) }
/>
</div>
);
}

save.js file:

import { __ } from '@wordpress/i18n';
import { useBlockProps } from '@wordpress/block-editor';
export default function save( { attributes } ) {
return <div { …useBlockProps.save() }>{ attributes.message }</div>;
}

Reload the editor and add the block after rebuilding the block using npm run build. In the editor, type a message, save it, and view it in the post.

4: Code Implementation

Now that the basic block is in place, it’s time to apply styles to it. Feel free to design and edit to your liking; the main point is to demonstrate how to generate and load external resources. We’ll use the colourized gilbert typeface from Type with Pride for this example.

Note that while the color may not function in all browsers until they support the correct color font, the typeface itself loads and styles. For more information on color fonts and browser support, go to colorfonts.wtf.

Load Font File:

Download the font from the Type with Pride website and save it as gilbert-color.otf in the src directory of your plugin. We need to use normal WordPress enqueue to load the font file.

The enqueue process is already configured from the produced script in the softhunt.php file, thus index.css and style-index.css files are loaded using:

function create_block_softhunt_block_init() {
register_block_type( DIR );
}
add_action( 'init', 'create_block_softhunt_block_init' );

This method looks for js and css files in the block.json file and passes them on to the enqueue function, which loads them on the relevant pages.

The build/index.css is built from src/editor.scss and only loaded after the style-index.css within the editor.
The build/style-index.css file is generated from the src/style.scss file and is loaded in the editor and front-end.

Add CSS Style for Block:

Because the style will be visible while editing and reading the article, we just need to add it to build/style-index.css. Add the following to the src/style.scss file.

The classname of the block is prefixed with wp-block. The classname.wp-block-create-block-softhunt is created from the create-block/softhunt.

@font-face {
font-family: Gilbert;
src: url( gilbert-color.otf );
font-weight: bold;
}
.wp-block-create-block-softhunt {
font-family: Gilbert;
font-size: 64px;
}

After upgrading, use npm run build to rebuild the block, then reload the article and refresh the browser. It will be styled if you are using a browser that supports color fonts (Firefox).

That’s all for this article if you have any queries please contact us through our website or email us at [email protected]

Leave a Comment