求助:WordPress中创建带服务端动态渲染回调的自定义Gutenberg区块后无内容显示
求助:WordPress中创建带服务端动态渲染回调的自定义Gutenberg区块后无内容显示
我之前也踩过这个一模一样的坑!你遇到的问题大概率是PHP端和JS端的区块配置没对齐,或者关联没做好,咱们一步步来排查修复:
首先,核心问题:PHP与JS的区块名称必须完全匹配
你JS里注册的区块名称是myplugin/dynamic-block,但PHP代码里用__DIR__ . '/my-block'这种目录方式注册时,如果这个目录里没有配置block.json文件,PHP根本不知道要关联到这个名称的区块,两边就彻底脱节了,自然看不到内容。
修复方案二选一:
方案1:改用参数式注册PHP区块(不用目录)
把你的PHP注册代码改成下面这样,直接把区块名称作为第一个参数,同时关联上JS脚本的句柄:
function myplugin_register_block() { // 先注册并关联编辑器JS脚本 $editor_script_path = get_stylesheet_directory_uri() . '/my-block/index.js'; // 换成你实际的JS文件路径 wp_register_script( 'myplugin-dynamic-block-editor-script', $editor_script_path, array( 'wp-blocks', 'wp-element', 'wp-editor' ), // 必须的Gutenberg依赖 filemtime( get_stylesheet_directory() . '/my-block/index.js' ), // 用文件修改时间避免缓存问题 true ); // 注册区块 register_block_type( 'myplugin/dynamic-block', array( 'render_callback' => 'myplugin_render_my_block', 'editor_script' => 'myplugin-dynamic-block-editor-script', // 和上面注册的脚本句柄对应 ) ); } add_action( 'init', 'myplugin_register_block' ); function myplugin_render_my_block( $attributes ) { return '<div class="dynamic-block">Hello, this is dynamic content!</div>'; }
方案2:保留目录式注册,添加block.json文件
在你的/my-block目录下创建block.json文件,至少包含以下内容,确保名称和JS里的完全一致:
{ "apiVersion": 3, "name": "myplugin/dynamic-block", "title": "我的动态区块", "category": "widgets", "editorScript": "file:./index.js" }
这样PHP读取目录时,就能通过这个文件识别到正确的区块名称,和JS端关联起来。
其次,优化编辑器预览的小细节
你的JS里的edit组件写法没问题,但可以加上useBlockProps让编辑器里的区块更符合Gutenberg的规范,避免一些奇怪的样式问题:
import { registerBlockType } from '@wordpress/blocks'; import { useBlockProps } from '@wordpress/block-editor'; registerBlockType('myplugin/dynamic-block', { edit: () => { const blockProps = useBlockProps(); return <p {...blockProps}>Hello from the editor!</p>; }, save: () => { return null; // 动态渲染的正确设置,不用改 }, });
最后,验证回调是否真的执行
你可以在渲染回调里加个调试日志,确认PHP端是否真的触发了这个函数:
function myplugin_render_my_block( $attributes ) { error_log('动态区块渲染回调已触发!'); // 去PHP错误日志里找这条记录 return '<div class="dynamic-block">Hello, this is dynamic content!</div>'; }
如果日志里能看到这条记录,说明前端到后端的通路已经通了,剩下的就是调整HTML输出就行。
你之前试过的刷新固定链接、检查函数名这些操作都是对的,把上面这些配置补上,应该就能看到编辑器的预览和前端的动态内容了。
内容来源于stack exchange
相关产品推荐
相关产品推荐

