如何一键在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
相关产品推荐
相关产品推荐

