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

WordPress Gutenberg插件区块翻译异常:wp_set_script_translations返回false

解决 wp_set_script_translations 返回 false 的问题

针对你开发的Cinc Blocks插件遇到的翻译加载失败问题,按以下步骤排查修正:

1. 脚本句柄错误

你当前使用的cinc-blocks-script是自定义句柄,但每个Gutenberg区块的脚本句柄由block.json自动生成,格式为{区块名称前缀}-{区块名}-editor-script(编辑器脚本)或{区块名称前缀}-{区块名}-script(前端脚本)。

修正方式:
注册区块后,直接获取返回对象中的脚本句柄,无需自定义:

function cinc_blocks_block_init() {
    // 注册区块并获取返回对象
    $document_block = register_block_type( __DIR__ . '/build/document' );
    $newsletter_block = register_block_type( __DIR__ . '/build/newsletter-form' );

    // 为编辑器脚本设置翻译
    if ( isset( $document_block->editor_script ) ) {
        wp_set_script_translations( $document_block->editor_script, 'cinc-blocks', plugin_dir_path( __FILE__ ) . 'languages' );
    }
    if ( isset( $newsletter_block->editor_script ) ) {
        wp_set_script_translations( $newsletter_block->editor_script, 'cinc-blocks', plugin_dir_path( __FILE__ ) . 'languages' );
    }

    // 如果区块有前端脚本,同步设置翻译
    if ( isset( $document_block->script ) ) {
        wp_set_script_translations( $document_block->script, 'cinc-blocks', plugin_dir_path( __FILE__ ) . 'languages' );
    }
    if ( isset( $newsletter_block->script ) ) {
        wp_set_script_translations( $newsletter_block->script, 'cinc-blocks', plugin_dir_path( __FILE__ ) . 'languages' );
    }
}
add_action( 'init', 'cinc_blocks_block_init' );

2. 钩子使用错误

原代码使用wp_enqueue_scripts钩子仅针对前台脚本,而Gutenberg编辑器的脚本翻译需要在脚本注册后立即加载,直接将翻译设置逻辑放在init钩子的区块注册代码后即可,无需单独钩子。

3. 翻译文件命名与生成问题

JSON翻译文件的命名格式必须为{text-domain}-{locale}-{script-handle-hash}.json,其中哈希值由WordPress根据脚本句柄自动生成,手动命名容易出错。

正确生成方式:
使用WP-CLI命令自动生成JSON文件:

wp i18n make-json languages/cinc-blocks-ca.po --no-purge

该命令会自动生成带正确哈希的JSON文件,确保与脚本句柄匹配。

4. 配置一致性检查

  • 确认插件头部的Text Domain: cinc-blocks与block.json中每个区块的"textDomain": "cinc-blocks"完全一致
  • 确认languages目录路径正确:用var_dump(plugin_dir_path( __FILE__ ) . 'languages')输出路径,检查是否指向插件根目录下的languages文件夹
  • 确认.pot文件包含所有区块的翻译字符串,.po文件已正确翻译并生成对应的.mo和JSON文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:53:24