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

使用WPML翻译管理翻译自定义Gutenberg区块遇阻求助

自定义Gutenberg区块适配WPML翻译的解决步骤

1. 注册区块时添加WPML支持标记

在区块的PHP注册代码里,必须明确标记区块支持WPML,并指定可翻译的属性字段:

register_block_type( 'your-namespace/your-block', array(
    'editor_script' => 'your-block-script',
    'render_callback' => 'your_block_render',
    'wpml_support' => true,
    'attributes' => array(
        'title' => array(
            'type' => 'string',
            'default' => '',
            'wpml_translatable' => true // 标记该字段可翻译
        ),
        'content' => array(
            'type' => 'string',
            'default' => '',
            'wpml_translatable' => true
        )
    )
) );

2. 用WPML API手动注册可翻译字段

如果自动标记不生效,可在区块渲染回调中直接调用WPML的注册函数:

function your_block_render( $attributes ) {
    // 注册标题字段
    if ( isset( $attributes['title'] ) && !empty( $attributes['title'] ) ) {
        do_action( 'wpml_register_single_string', 'Your Block', 'Block Title: ' . get_the_ID(), $attributes['title'] );
    }
    // 注册内容字段
    if ( isset( $attributes['content'] ) && !empty( $attributes['content'] ) ) {
        do_action( 'wpml_register_single_string', 'Your Block', 'Block Content: ' . get_the_ID(), $attributes['content'] );
    }

    // 渲染时调用翻译过滤器
    return '<div class="your-block">
        <h2>' . apply_filters( 'wpml_translate_single_string', $attributes['title'], 'Your Block', 'Block Title: ' . get_the_ID() ) . '</h2>
        <p>' . apply_filters( 'wpml_translate_single_string', $attributes['content'], 'Your Block', 'Block Content: ' . get_the_ID() ) . '</p>
    </div>';
}

3. 检查WPML后台设置

  • 进入WPML → 设置 → 自定义字段翻译,找到区块属性对应的自定义字段(格式一般是block_your-namespace/your-block_title),设置为「可翻译」
  • 在WPML翻译管理界面,确认已开启「翻译自定义字段」选项

4. 清除区块缓存

  • 进入WordPress后台「工具」→「站点健康」→「信息」→「媒体」,点击「清除Gutenberg区块缓存」
  • 重新编辑包含自定义区块的文章并保存,再进入WPML翻译管理界面查看

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 20:01:06