能否用纯PHP开发带区块的WordPress插件?代码排查与属性检测
纯PHP开发WordPress自定义区块的问题排查与解决方案
一、区块未在编辑器显示的排查要点
WordPress区块编辑器(Gutenberg)核心依赖JS/React,纯PHP仅能处理区块的前端渲染与数据保存,编辑器端的区块注册必须配合基础JS代码(哪怕极简),否则编辑器无法识别区块。以下是常见遗漏点:
缺少区块核心定义配置
- 未创建
block.json文件:WordPress 5.8+推荐用该文件声明区块基本信息(名称、图标、分类、编辑器脚本等),示例:{ "$schema": "https://schemas.wp.org/trunk/block.json", "apiVersion": 3, "name": "my-plugin/custom-block", "title": "我的自定义区块", "category": "widgets", "icon": "smiley", "editorScript": "file:./editor.js", "render": "file:./render.php" } - 若未用
block.json,需在register_block_type()中明确设置editor_script,指向一段极简的JS注册代码。
- 未创建
PHP注册逻辑错误
- 未在
init钩子中调用register_block_type():add_action('init', function() { // 方式1:通过block.json注册 register_block_type(__DIR__ . '/block.json'); // 方式2:直接传数组参数注册 // register_block_type('my-plugin/custom-block', [ // 'editor_script' => 'my-block-editor-script', // 'render_callback' => 'my_block_render' // ]); }); - 未正确注册编辑器脚本:哪怕是极简JS也要注册并关联到区块,示例JS代码(editor.js):
对应PHP注册脚本代码:wp.blocks.registerBlockType('my-plugin/custom-block', { title: '我的自定义区块', category: 'widgets', icon: 'smiley', edit: () => wp.element.createElement('div', {}, '编辑器内预览'), save: () => null // 由PHP的render_callback处理前端渲染 });add_action('init', function() { wp_register_script( 'my-block-editor-script', plugin_dir_url(__FILE__) . 'editor.js', ['wp-blocks', 'wp-element'], filemtime(plugin_dir_path(__FILE__) . 'editor.js') ); register_block_type('my-plugin/custom-block', [ 'editor_script' => 'my-block-editor-script', 'render_callback' => 'my_block_render' ]); });
- 未在
权限与缓存问题
- 检查当前用户是否拥有
edit_posts权限(编辑器默认访问权限); - 清除WordPress缓存与浏览器缓存,确保新注册区块被加载。
- 检查当前用户是否拥有
二、区块属性与选中样式的检测方案
1. get_block_attributes()无法在编辑回调中使用的原因
get_block_attributes()是PHP端函数,仅能在区块的render_callback或数据保存阶段调用,编辑器的编辑环境是JS/React,无法直接执行PHP函数。
2. 获取区块属性的正确方式
PHP端(渲染/保存时)
在render_callback中,第一个参数即为区块属性数组,直接调用即可:
function my_block_render($attributes) { // 读取自定义属性,比如背景色 $bg_color = isset($attributes['backgroundColor']) ? $attributes['backgroundColor'] : '#ffffff'; return '<div style="background-color: ' . esc_attr($bg_color) . ';">' . $attributes['content'] . '</div>'; }
编辑器端(JS/React,检测选中样式)
若需在编辑器中实时检测区块选中状态或样式,需在JS的edit组件中处理:
- 获取当前区块属性:通过
edit函数的参数直接读取attributes; - 判断选中状态:使用
isSelected参数直接判定; - 读取样式属性:从
attributes中读取backgroundColor、textColor、style等字段,或解析className中的预设样式类。
示例JS代码:
wp.blocks.registerBlockType('my-plugin/custom-block', { attributes: { content: { type: 'string', source: 'html', selector: 'div' }, backgroundColor: { type: 'string' } }, edit: ({ attributes, setAttributes, isSelected }) => { const currentBg = attributes.backgroundColor; return wp.element.createElement( 'div', { style: { backgroundColor: currentBg || '#f0f0f0' }, className: isSelected ? 'selected-highlight' : '' }, '编辑器预览区域' ); }, save: () => null });
3. 选中文本样式检测补充
若需获取编辑器中选中文本的样式(而非区块本身),可结合wp.data.select('core/editor').getSelection()与document.getSelection()来读取选中内容的CSS样式。
内容的提问来源于stack exchange,提问作者Danijela Popović
相关产品推荐
相关产品推荐

