You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gutenberg块编辑器CPT中创建通知无法显示的问题求助

问题解决步骤

1. 修复脚本入队的依赖与加载条件

出现cant find variable wp是因为你的脚本没有依赖WordPress提供的Gutenberg核心脚本,导致wp对象还未加载就执行了代码。同时要确保脚本只在Gutenberg编辑器页面加载,避免不必要的资源浪费:

add_action("admin_enqueue_scripts", function(){
    $screen = get_current_screen();
    // 仅在文章/页面/自定义文章类型的Gutenberg编辑页面加载脚本
    if ( $screen && $screen->is_block_editor() ) {
        wp_enqueue_script(
            "ownNotice_admin_script",
            PLUGIN_URL . "/assets/admin/js/test.js",
            array( 'wp-data', 'wp-notices' ), // 添加Gutenberg核心依赖
            '1',
            true // 在页脚加载,确保wp对象已初始化
        );
    }
});

2. 修改JavaScript代码,确保在编辑器就绪后执行

直接执行wp.data.dispatch会因为Gutenberg还未完成初始化而失效,需要包裹在编辑器就绪的回调中,同时修正拼写错误:

// 等待Gutenberg编辑器初始化完成
wp.domReady( function() {
    wp.data.dispatch( 'core/notices' ).createNotice(
        'warning',
        'Please fill all fields', // 修正filds为fields
        { 
            id: 'stFilAll', 
            isDismissible: true
        }
    );
} );

3. 额外验证:针对自定义文章类型的特殊处理

如果你的通知需要在特定自定义文章类型(CPT)的编辑页面显示,可以在PHP入队时增加CPT判断:

add_action("admin_enqueue_scripts", function(){
    $screen = get_current_screen();
    // 替换为你的自定义文章类型slug
    $target_cpt = 'your_custom_post_type';
    if ( $screen && $screen->is_block_editor() && $screen->post_type === $target_cpt ) {
        wp_enqueue_script(
            "ownNotice_admin_script",
            PLUGIN_URL . "/assets/admin/js/test.js",
            array( 'wp-data', 'wp-notices' ),
            '1',
            true
        );
    }
});

这样修改后,脚本会在正确的时机加载,wp对象能被正常访问,通知也会在Gutenberg编辑器中显示出来。

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:55:04