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

如何一键在WordPress中为文本添加指定span标签?

解决WordPress Gutenberg添加带data-no-translation属性的span标签问题

你的代码问题出在格式类型的注册配置上,下面是修正后的完整方案:

修正后的JavaScript代码

(function (wp) {
    const { createElement } = wp.element;
    const { RichTextToolbarButton } = wp.blockEditor;
    const { registerFormatType, toggleFormat } = wp.richText;

    const NoTranslateButton = (props) => {
        return createElement(
            RichTextToolbarButton,
            {
                icon: 'editor-code',
                title: 'No Translate',
                onClick: () => {
                    props.onChange(toggleFormat(
                        props.value,
                        { type: 'my-plugin/no-translate' }
                    ));
                },
                isActive: props.isActive,
            }
        );
    };

    registerFormatType(
        'my-plugin/no-translate',
        {
            title: 'No Translate',
            tagName: 'span',
            attributes: {
                'data-no-translation': {
                    source: 'attribute',
                    attribute: 'data-no-translation',
                    default: ''
                }
            },
            edit: NoTranslateButton,
        }
    );
})(window.wp);

关键修改点

  • 移除className: 'no-translation':这是之前生成<span class="no-translation">的核心原因,你的需求不需要该class,直接删除即可。
  • 完善attributes配置:明确指定data-no-translation属性的来源为标签属性,并设置默认值为空字符串,确保生成你需要的<span data-no-translation="">格式。
  • 语义化变量名:将MyCustomButton改为NoTranslateButton,提升代码可读性和维护性。

PHP代码确认

你的functions.php代码没有问题,只要确保脚本路径和文件名匹配,就能正常在编辑器中加载自定义JS。

使用效果

现在在Gutenberg编辑器中选中文本,点击工具栏的"No Translate"按钮,就能自动给选中内容包裹上<span data-no-translation=""></span>标签,完美适配TranslatePress的防翻译需求,避免内部URL被自动转换为其他语言版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:27:22