使用React(Gutenberg)将后台Featured image面板从侧边移至内容下方
将Gutenberg编辑器中的特色图片面板移至内容下方
由于Gutenberg编辑器采用了与传统经典编辑器不同的面板管理机制,你之前找到的PHP方法无法生效,需要通过JavaScript结合WordPress的Block Editor API来实现需求。
实现步骤:
- 添加PHP代码注册脚本
在主题的functions.php文件中加入以下代码,用于在后台编辑器加载自定义JavaScript:
function move_featured_image_panel() { if ( is_admin() ) { wp_enqueue_script( 'move-featured-image', get_template_directory_uri() . '/js/move-featured-image.js', array( 'wp-blocks', 'wp-edit-post', 'wp-element' ), wp_get_theme()->get('Version'), true ); } } add_action( 'enqueue_block_editor_assets', 'move_featured_image_panel' );
如果使用子主题,将get_template_directory_uri()替换为get_stylesheet_directory_uri()。
- 创建JavaScript文件
在主题目录下新建js文件夹,创建move-featured-image.js文件并写入以下代码:
const { registerPlugin } = wp.plugins; const { PluginDocumentSettingPanel } = wp.editPost; const { PostFeaturedImage } = wp.editor; const { dispatch } = wp.data; registerPlugin( 'move-featured-image-panel', { render() { // 移除默认侧边栏的特色图片面板 dispatch('core/edit-post').removeEditorPanel('featured-image'); // 在内容区域下方重新添加特色图片面板 return ( <PluginDocumentSettingPanel name="featured-image-below-content" title="特色图片" position="normal" > <PostFeaturedImage /> </PluginDocumentSettingPanel> ); }, } );
代码说明:
dispatch('core/edit-post').removeEditorPanel('featured-image'):移除Gutenberg默认在侧边栏显示的特色图片面板。PluginDocumentSettingPanel是Block Editor提供的面板组件,position="normal"参数指定面板显示在内容编辑区域的下方(side为侧边栏位置)。PostFeaturedImage是官方的特色图片组件,确保功能与默认面板完全一致。
注意事项:
- 确保JavaScript文件路径正确,若路径不符需调整
get_template_directory_uri()后的路径部分。 - 修改代码后清空浏览器缓存和WordPress后台缓存,避免旧代码干扰。
内容的提问来源于stack exchange,提问作者Katia Kovtun
相关产品推荐
相关产品推荐

