
本文介绍如何在 Gutenberg 区块的编辑器界面中,通过 React + @wordpress/data API 动态获取并渲染所有可查看的文章类型(包括自定义文章类型),构建专业、响应式的 下拉组件,并正确绑定至区块属性。
本文介绍如何在 gutenberg 区块的编辑器界面中,通过 react + `@wordpress/data` api 动态获取并渲染所有可查看的文章类型(包括自定义文章类型),构建专业、响应式的 `
在开发 Gutenberg 自定义区块时,若需让用户从所有注册的文章类型(如 post、page 或自定义类型 product、event)中进行选择,不推荐硬编码选项或依赖 PHP 渲染——这会破坏区块的客户端一致性与可维护性。正确做法是利用 WordPress 数据模块(@wordpress/core-data)提供的 getPostTypes() 方法,在编辑器端实时拉取、过滤并格式化数据。
✅ 核心实现步骤
- 声明区块属性:在 block.json 中定义 postType 字符串属性,设默认值(如 "post");
- 在 edit.js 中调用数据源:使用 useSelect 钩子从 coreStore 获取文章类型列表;
- 过滤与格式化选项:仅保留 viewable: true 的类型(排除 wp_block、wp_navigation 等内部类型),并映射为 { label, value } 结构;
-
渲染
:绑定当前值与变更事件,实现双向属性同步。
? 完整代码示例
block.json(关键片段)
{
"apiVersion": 3,
"name": "my-plugin/post-type-selector",
"title": "Post Type Selector",
"attributes": {
"postType": {
"type": "string",
"default": "post"
}
}
}edit.js
import { useSelect } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { SelectControl } from '@wordpress/components';
import { useBlockProps } from '@wordpress/block-editor';
export default function Edit({ attributes, setAttributes }) {
const { postType } = attributes;
// 获取所有文章类型(含自定义类型),-1 表示不限数量
const postTypes = useSelect(
(select) => select(coreStore).getPostTypes({ per_page: -1 }),
[]
);
// 过滤 + 格式化:仅保留可查看类型,并转换为 SelectControl 所需结构
const postTypeOptions = Array.isArray(postTypes)
? postTypes
.filter((type) => type.viewable === true)
.map((type) => ({
label: type.labels?.singular_name || type.name,
value: type.slug,
}))
: [];
return (
<div {...useBlockProps()}>
<SelectControl
label="选择文章类型"
help="将用于查询对应类型的文章列表"
value={postType}
options={postTypeOptions}
onChange={(value) => setAttributes({ postType: value })}
/>
</div>
);
}⚠️ 注意事项与最佳实践
- 权限与可见性:getPostTypes() 默认仅返回当前用户有读取权限且 show_in_rest: true 的类型。确保你的自定义文章类型在注册时已启用 REST API 支持('show_in_rest' => true);
- 性能优化:useSelect 的第二个参数 [] 是依赖数组,此处为空表示仅在组件挂载时执行一次请求,避免重复渲染开销;
-
空状态处理:postTypeOptions 可能为空数组(如无可用类型),建议在 UI 层添加兜底提示(例如 options.length === 0 &&
暂无可用文章类型
); - UI 位置建议:该控件更适合置于 Settings Sidebar(设置侧边栏)而非主编辑区域,以符合 Gutenberg 设计规范。可通过 InspectorControls 组件包裹实现;
- 服务端验证:前端选择仅影响编辑体验,保存后务必在 PHP 的 render_callback 或 save 函数中对 attributes.postType 做合法性校验,防止恶意输入。
通过以上方式,你不仅能无缝支持任意主题或插件注册的自定义文章类型,还能保持与 Gutenberg 原生 UI 的高度一致性,为用户提供专业、可靠的操作体验。










