如何修改Gutenberg core/file块变体的占位标签与说明文本
解决Gutenberg core/file区块变体默认占位文本无法修改的问题
core/file区块的默认占位文本("Upload a file or pick one from your media library.")是在区块编辑组件内部硬编码的,没法通过变体注册时的属性直接修改,得用过滤器拦截渲染逻辑或者替换文本。
方法一:通过editor.BlockEdit过滤器精准替换变体占位内容
这种方法只针对你的目标变体生效,不会影响其他core/file区块实例:
wp.hooks.addFilter( 'editor.BlockEdit', 'your-custom-namespace/file-variant-placeholder', ( BlockEdit, props ) => { // 替换成你注册变体时设置的name值 const targetVariation = 'your-file-variant-name'; if ( props.name === 'core/file' && props.attributes.variationName === targetVariation ) { return wp.element.createElement( wp.element.Fragment, null, wp.element.cloneElement( <BlockEdit { ...props } />, {}, // 遍历子组件,定位占位符元素并替换文本 React.Children.map( ( <BlockEdit { ...props } /> ).props.children, child => { if ( child.props?.className === 'components-placeholder' ) { return wp.element.cloneElement( child, {}, wp.element.createElement( 'div', { className: 'components-placeholder__label' }, '自定义标题' ), wp.element.createElement( 'div', { className: 'components-placeholder__instructions' }, '你的自定义提示文本,比如「上传文件或从媒体库选择」' ) ); } return child; } ) ) ); } return BlockEdit; } );
方法二:通过i18n.gettext过滤器修改翻译文本
如果需要批量修改但要限定在目标变体上,可以用翻译过滤器:
wp.hooks.addFilter( 'i18n.gettext', 'your-custom-namespace/file-placeholder-translation', ( translation, text, domain ) => { const targetVariation = 'your-file-variant-name'; const selectedBlock = wp.data.select('core/editor').getSelectedBlock(); // 仅在选中目标变体时替换指定文本 if ( domain === 'default' && text === 'Upload a file or pick one from your media library.' && selectedBlock?.name === 'core/file' && selectedBlock?.attributes.variationName === targetVariation ) { return '你的自定义提示文本'; } return translation; } );
注意事项
- 把代码里的
your-file-variant-name替换成你注册变体时设置的name属性值 - 方法一可直接使用Gutenberg内置的
React或wp.element对象 - 方法二依赖编辑器选中状态,只有区块被选中时才会替换文本
内容的提问来源于stack exchange,提问作者Simon
相关产品推荐
相关产品推荐

