WordPress如何在后台文章编辑页侧边栏新增带自定义meta box的标签
可以实现,不过古腾堡编辑器的侧边栏标签无法通过传统PHP添加meta box的方式实现,需要配合古腾堡的JS扩展API完成,操作步骤如下:
第一步:注册可通过REST API读写的自定义字段
首先需要在主题functions.php中添加代码注册自定义字段,否则侧边栏修改的内容无法正常保存到文章元数据:
function custom_register_post_meta() { register_post_meta( 'post', 'custom_field_key', array( 'show_in_rest' => true, 'single' => true, 'type' => 'string', 'auth_callback' => function() { return current_user_can( 'edit_posts' ); } ) ); } add_action( 'init', 'custom_register_post_meta' );
第二步:加载古腾堡编辑器扩展脚本
继续在functions.php中添加代码,将自定义JS脚本注入到文章编辑页:
function custom_enqueue_editor_script() { $screen = get_current_screen(); if ( $screen->base === 'post' ) { wp_enqueue_script( 'custom-sidebar-tab', get_template_directory_uri() . '/js/custom-sidebar-tab.js', // 替换为你自己的JS文件实际路径 array( 'wp-edit-post', 'wp-element', 'wp-plugins', 'wp-components', 'wp-i18n' ), filemtime( get_template_directory() . '/js/custom-sidebar-tab.js' ), true ); wp_set_script_translations( 'custom-sidebar-tab', 'custom' ); } } add_action( 'enqueue_block_editor_assets', 'custom_enqueue_editor_script' );
第三步:编写侧边栏标签逻辑
在你指定的JS文件路径下新建custom-sidebar-tab.js,写入如下代码:
import { __ } from '@wordpress/i18n'; import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/edit-post'; import { registerPlugin } from '@wordpress/plugins'; import { PanelBody, TextControl } from '@wordpress/components'; import { useSelect, useDispatch } from '@wordpress/data'; const CustomSidebarTab = () => { // 读取已保存的自定义字段值 const customFieldValue = useSelect( ( select ) => { return select( 'core/editor' ).getEditedPostAttribute( 'meta' )?.custom_field_key || ''; }, [] ); const { editPost } = useDispatch( 'core/editor' ); return ( <> {/* 侧边栏更多菜单入口 */} <PluginSidebarMoreMenuItem target="custom-sidebar-tab" > { __( '自定义设置', 'custom' ) } </PluginSidebarMoreMenuItem> {/* 侧边栏标签页主体 */} <PluginSidebar name="custom-sidebar-tab" title={ __( '自定义设置', 'custom' ) } icon="admin-settings" // 可替换为任意WordPress内置dashicons图标名 > <PanelBody> <TextControl label={ __( '自定义字段内容', 'custom' ) } value={ customFieldValue } onChange={ ( val ) => { editPost( { meta: { custom_field_key: val } } ) } } /> {/* 此处可添加更多你需要的表单控件,匹配之前meta box的功能 */} </PanelBody> </PluginSidebar> </> ); }; // 注册插件 registerPlugin( 'custom-sidebar-tab', { render: CustomSidebarTab } );
添加完成后刷新文章编辑页,即可在侧边栏看到和「Block」标签平行的自定义标签页,功能可根据需求自行扩展。
内容的提问来源于stack exchange,提问作者webmastx
相关产品推荐
相关产品推荐

