0
0
Wordpressframework~5 mins

Block registration in Wordpress

Choose your learning style9 modes available
Introduction

Block registration lets you add new blocks to the WordPress editor. This helps you create custom content pieces easily.

You want to add a special content block like a testimonial or a call-to-action.
You need a reusable block with custom settings for your website.
You want to create a block that matches your brand style and layout.
You want to extend the editor with blocks that show dynamic data.
You want to simplify content creation for editors with custom blocks.
Syntax
Wordpress
registerBlockType('namespace/block-name', {
  title: 'Block Title',
  icon: 'smiley',
  category: 'common',
  edit: () => {
    return <p>Hello from the block editor!</p>;
  },
  save: () => {
    return <p>Hello from the saved content!</p>;
  },
});

The first argument is a unique name with a namespace and block name separated by a slash.

The edit function defines what appears in the editor, and save defines what is saved in the post content.

Examples
This example creates a yellow alert box block with a warning icon.
Wordpress
registerBlockType('myplugin/alert', {
  title: 'Alert Box',
  icon: 'warning',
  category: 'widgets',
  edit: () => <div style={{backgroundColor: 'yellow', padding: '10px'}}>Alert in editor</div>,
  save: () => <div style={{backgroundColor: 'yellow', padding: '10px'}}>Alert on page</div>,
});
A simple text block that shows the same text in editor and saved content.
Wordpress
registerBlockType('myplugin/simple-text', {
  title: 'Simple Text',
  icon: 'text',
  category: 'text',
  edit: () => <p>Type your text here</p>,
  save: () => <p>Type your text here</p>,
});
Sample Program

This block shows a button in the editor that counts clicks. The saved content is a simple button text because saved content can't have dynamic state.

Wordpress
import { registerBlockType } from '@wordpress/blocks';
import { useState } from '@wordpress/element';

registerBlockType('myplugin/click-counter', {
  title: 'Click Counter',
  icon: 'smiley',
  category: 'widgets',
  edit: () => {
    const [count, setCount] = useState(0);
    return (
      <button onClick={() => setCount(count + 1)} aria-label="Click counter button">
        Clicked {count} times
      </button>
    );
  },
  save: () => {
    return <button>Click counter saved block</button>;
  },
});
OutputSuccess
Important Notes

Blocks must have a unique name with a namespace to avoid conflicts.

The edit function can use React hooks like useState for interactivity in the editor.

The save function returns static content that is saved in the post and shown on the site.

Summary

Block registration adds custom blocks to the WordPress editor.

Use registerBlockType with a unique name and provide edit and save functions.

Blocks help create rich, reusable content easily for editors and visitors.