WordPress定制器中自定义Gutenberg块小部件不支持问题
问题现象
自定义Gutenberg块在后台仪表盘、小部件管理区域均可正常使用,但进入WordPress定制器编辑小部件时,弹出错误提示:
Your site doesn’t include support for the "widgetsplugin/info-top-header-widget" block. You can leave this block intact or remove it entirely.
解决方案
问题根源是定制器环境未加载块的JavaScript脚本,WordPress定制器有独立的钩子体系,需额外处理脚本加载:
1. 添加定制器专属钩子加载脚本
修改插件的PHP代码,在原有init钩子基础上,新增两个定制器相关钩子,确保块脚本在定制器的控制面板和预览环境都能加载:
// 保留原有init钩子 add_action('init', [$this, 'myInit']); // 新增定制器钩子 add_action('customize_preview_init', [$this, 'enqueue_block_for_customizer']); add_action('customize_controls_enqueue_scripts', [$this, 'enqueue_block_for_customizer']); function myInit() { wp_enqueue_script( 'pluginsscriptwidgets', plugin_dir_url(__FILE__) . 'build/index.js', ['wp-blocks', 'wp-element', 'wp-editor', 'wp-dom-ready', 'wp-customize-widgets'], // 新增wp-customize-widgets依赖 filemtime(plugin_dir_path(__FILE__) . 'build/index.js'), // 可选:添加版本号避免缓存 true ); register_block_type('widgetsplugin/info-top-header-widget', [ 'render_callback' => [$this, 'TopHeaderInfoWidget_HTML'] ]); } function enqueue_block_for_customizer() { // 重复加载块脚本(定制器环境需要) wp_enqueue_script( 'pluginsscriptwidgets', plugin_dir_url(__FILE__) . 'build/index.js', ['wp-blocks', 'wp-element', 'wp-editor', 'wp-dom-ready', 'wp-customize-widgets'], filemtime(plugin_dir_path(__FILE__) . 'build/index.js'), true ); } function TopHeaderInfoWidget_HTML($attributes) { return TopHeaderInfo_HTML($attributes); }
2. 确认块注册名称一致性
确保PHP中register_block_type的块名(widgetsplugin/info-top-header-widget)与JS中wp.blocks.registerBlockType的名称完全一致,你的现有代码已经符合要求,无需修改。
3. 补充脚本依赖
在wp_enqueue_script的依赖数组中添加wp-customize-widgets,这个模块是定制器编辑小部件的核心依赖,缺失会导致块无法被识别。
原理说明
WordPress定制器的加载流程与后台仪表盘独立,init钩子加载的脚本不会自动覆盖定制器环境。通过customize_preview_init(预览区域)和customize_controls_enqueue_scripts(控制面板)钩子,强制在定制器环境中加载块的JS脚本,同时补充必要的依赖,让定制器能够识别并渲染自定义块的编辑界面。
内容的提问来源于stack exchange,提问作者zakaryaaghlaoui

