WordPress Block Development
WordPress Block Development involves creating custom blocks for the WordPress Block Editor (Gutenberg) using React, JavaScript, and PHP. Blocks enhance the content editing experience by allowing users to add structured elements to their pages and posts.
Steps to Create a Custom Block
1. Setup a WordPress Plugin for the Block
Each block is typically created as a WordPress plugin.
Create a plugin folder in WordPress Plugin Directory
wp-custom-block (Plugin Directory Name)
Inside the folder, create wp-custom-block.php (Plugin File)
<?php
/**
* Plugin Name: Custom Gutenberg Block
* Description: A simple Gutenberg block example.
* Version: 1.0
* Author: Your Name
*/
function custom_block_assets() {
wp_enqueue_script(
'custom-block',
plugins_url('build/index.js', __FILE__),
array('wp-blocks', 'wp-element', 'wp-editor'),
filemtime(plugin_dir_path(__FILE__) . 'build/index.js')
);
}
add_action('enqueue_block_editor_assets', 'custom_block_assets');
?>
领英推荐
2. Setup Package.json and Install Dependencies
Run the following commands:
npm init -y
npm install @wordpress/scripts --save-dev
Open package.json file and add below lines
"scripts": {
"start": "wp-scripts start",
"build": "wp-scripts build"
}
3. Register the Block (index.js)
Inside a src/ folder, create index.js:
import { registerBlockType } from '@wordpress/blocks';
import { RichText } from '@wordpress/block-editor';
registerBlockType('custom/hello-world', {
title: 'Hello World Block',
icon: 'smiley',
category: 'common',
attributes: {
content: { type: 'string', source: 'html', selector: 'p' }
},
edit: ({ attributes, setAttributes }) => {
return (
<RichText
tagName="p"
value={attributes.content}
onChange={(content) => setAttributes({ content })}
placeholder="Write something..."
/>
);
},
save: ({ attributes }) => {
return <RichText.Content tagName="p" value={attributes.content} />;
}
});
4. Build and Activate the Block
Run:
npm run build