WordPress自定义块开发教程,从入门到精通

来自:素雅营销研究院

头像 方知笔记
2025年05月24日 03:45

引言

WordPress 5.0 引入了全新的编辑器 Gutenberg,它基于区块(Block)的概念,让内容编辑更加灵活。然而,默认的区块可能无法满足所有需求,因此开发自定义区块成为许多 WordPress 开发者的必备技能。本文将带你一步步学习如何开发 WordPress 自定义块,从环境搭建到最终发布。

准备工作

在开始开发之前,确保你的环境满足以下条件:

  1. WordPress 5.0+:Gutenberg 编辑器需要较新版本的 WordPress。
  2. Node.js 和 npm:用于构建和编译前端代码。
  3. 代码编辑器:如 VS Code、Sublime Text 等。

步骤 1:创建插件目录

自定义区块通常以插件形式存在。在 wp-content/plugins 目录下创建一个新文件夹,例如 my-custom-block,并在其中创建以下文件:

my-custom-block/
├── my-custom-block.php (主插件文件)
├── src/ (存放前端代码)
│   └── index.js (区块的 JavaScript 入口)
├── build/ (编译后的文件)
└── package.json (Node.js 依赖管理)

步骤 2:初始化插件

my-custom-block.php 中写入以下代码,注册插件:

<?php
/**
* Plugin Name: My Custom Block
* Description: 一个自定义的 WordPress 区块。
* Version: 1.0.0
*/

function my_custom_block_init() {
register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'my_custom_block_init' );

步骤 3:配置前端开发环境

在插件目录下运行以下命令初始化 package.json

npm init -y
npm install @wordpress/scripts --save-dev

修改 package.json,添加构建脚本:

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

步骤 4:编写自定义区块代码

src/index.js 中编写区块逻辑:

import { registerBlockType } from '@wordpress/blocks';
import { TextControl } from '@wordpress/components';

registerBlockType('my-custom-block/hello-world', {
title: 'Hello World Block',
icon: 'smiley',
category: 'common',
attributes: {
content: {
type: 'string',
default: 'Hello, WordPress!'
}
},
edit: ({ attributes, setAttributes }) => {
return (
<TextControl
label="输入内容"
value={attributes.content}
onChange={(content) => setAttributes({ content })}
/>
);
},
save: ({ attributes }) => {
return <p>{attributes.content}</p>;
},
});

步骤 5:编译并测试

运行以下命令编译代码:

npm run build

然后在 WordPress 后台激活插件,并在 Gutenberg 编辑器中搜索 “Hello World Block” 测试你的自定义区块。

进阶功能

  1. 添加样式:通过 editor.cssstyle.css 分别控制编辑器和前端的样式。
  2. 动态渲染:使用 PHP 动态渲染区块内容(需在 block.json 中配置)。
  3. 国际化支持:通过 @wordpress/i18n 实现多语言支持。

结语

你已经学会了如何开发一个简单的 WordPress 自定义区块。随着深入实践,你可以创建更复杂的区块,甚至发布到 WordPress 插件库供他人使用。Happy Coding!