To create a custom sidebar in Gutenberg and have it open, you generally don’t “replace” the Block Settings sidebar directly, as the Block Settings are dynamic and context-sensitive to the selected block. Instead, you add your own custom sidebar alongside the existing ones. WordPress provides the tools to register and manage these custom sidebars within the Gutenberg editor.
Here’s a guide with code examples to help you create a custom sidebar. This involves two main parts: a PHP file (typically in your theme’s functions.php
or a custom plugin) to enqueue your JavaScript, and a JavaScript file where the actual sidebar logic resides.
1. PHP Code (in your functions.php
or a custom plugin file)
This PHP code will enqueue your JavaScript file, ensuring it loads in the Gutenberg editor.
<?php /** * Enqueue custom Gutenberg sidebar script. */ function my_custom_gutenberg_sidebar_enqueue() { // Enqueue the script for the block editor. // 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data' are essential dependencies. wp_enqueue_script( 'my-custom-gutenberg-sidebar', // Unique handle for your script get_template_directory_uri() . '/js/custom-sidebar.js', // Path to your JS file array( 'wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data' ), // Dependencies filemtime( get_template_directory() . '/js/custom-sidebar.js' ), // Version based on file modification time for cache busting true // Load script in the footer ); } add_action( 'enqueue_block_editor_assets', 'my_custom_gutenberg_sidebar_enqueue' ); /** * Register a custom meta field for demonstration purposes. * This meta field will be used by our custom sidebar. */ function my_custom_sidebar_register_meta() { register_post_meta( 'post', '_my_custom_sidebar_text', array( 'show_in_rest' => true, // Make sure it's accessible via REST API 'single' => true, // Store as a single value 'type' => 'string', // Data type 'auth_callback' => function() { // Authentication callback for saving return current_user_can( 'edit_posts' ); }, ) ); } add_action( 'init', 'my_custom_sidebar_register_meta' );
Explanation of the PHP Code:
my_custom_gutenberg_sidebar_enqueue()
: This function is hooked intoenqueue_block_editor_assets
, which is the correct action to load scripts specifically for the Gutenberg editor.wp_enqueue_script()
: Registers and enqueues your JavaScript file.- The dependencies (
wp-plugins
,wp-edit-post
,wp-element
,wp-components
,wp-data
) are crucial as they provide the necessary React components and WordPress data store utilities for building your sidebar. get_template_directory_uri() . '/js/custom-sidebar.js'
assumes your JavaScript file is located in ajs
folder within your active theme. Adjust the path if it’s elsewhere (e.g., in a plugin).
- The dependencies (
my_custom_sidebar_register_meta()
: This function registers a custom post meta field (_my_custom_sidebar_text
). This is important if your sidebar needs to save or retrieve data associated with the post.show_in_rest => true
: Makes the meta field accessible via the WordPress REST API, which Gutenberg uses to interact with data.auth_callback
: Ensures that only users with appropriate permissions can save this meta field.
2. JavaScript Code (e.g., theme-folder/js/custom-sidebar.js
)
This JavaScript code will define your custom sidebar using React components provided by WordPress.
// Import necessary WordPress packages const { registerPlugin } = wp.plugins; const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost; const { PanelBody, TextControl } = wp.components; const { Fragment } = wp.element; const { select, useDispatch } = wp.data; // For interacting with the data store const { useSelect, useDispatch: useDataDispatch } = wp.data; // For functional components /** * Custom Sidebar Component * This is the React component that will render the content of your sidebar. */ const MyCustomSidebar = () => { // Use useSelect to get the current post meta value const customText = useSelect( ( data ) => { return data.select( 'core/editor' ).getEditedPostAttribute( 'meta' )?._my_custom_sidebar_text; }, [] ); // Use useDispatch to get the action to update post meta const { editPost } = useDataDispatch( 'core/editor' ); // Function to update the custom meta field const updateCustomText = ( newValue ) => { editPost( { meta: { _my_custom_sidebar_text: newValue } } ); }; return ( <Fragment> {/* PluginSidebarMoreMenuItem adds an item to the "..." (More Tools & Options) menu */} <PluginSidebarMoreMenuItem target="my-custom-sidebar-panel" // Must match the name of PluginSidebar icon="admin-post" // Dashicon to display in the menu > My Custom Sidebar </PluginSidebarMoreMenuItem> {/* PluginSidebar defines the actual sidebar panel */} <PluginSidebar name="my-custom-sidebar-panel" // Unique name for your sidebar title="My Custom Sidebar" // Title displayed at the top of the sidebar icon="admin-post" // Dashicon to display in the sidebar header > <PanelBody title="Custom Settings" initialOpen={ true }> <TextControl label="Enter Custom Text" value={ customText || '' } // Display current value or empty string onChange={ updateCustomText } // Update function help="This text will be saved as post meta." /> <p> This is a custom sidebar. You can add any React components here to create your own settings and controls. </p> </PanelBody> </PluginSidebar> </Fragment> ); }; // Register your custom plugin/sidebar registerPlugin( 'my-custom-gutenberg-sidebar-plugin', { render: MyCustomSidebar, } ); // Optional: Automatically open the custom sidebar when the editor loads // Note: This might not always be desired as it can interfere with user flow. // It's generally better to let the user open it via the icon. /* wp.data.dispatch('core/edit-post').openGeneralSidebar('my-custom-sidebar-panel'); */
Explanation of the JavaScript Code:
- Imports:
wp.plugins
: ProvidesregisterPlugin
to register your custom functionality as a Gutenberg plugin.wp.editPost
: ProvidesPluginSidebar
(for the sidebar panel itself) andPluginSidebarMoreMenuItem
(for the menu item that opens it).wp.components
: Provides standard UI components likePanelBody
(for collapsible sections) andTextControl
(for text input fields).wp.element
: ProvidesFragment
(similar to React’sFragment
for grouping elements without adding extra DOM nodes).wp.data
: ProvidesuseSelect
anduseDispatch
hooks for interacting with the WordPress data store, allowing you to get and set post attributes (like custom meta).
MyCustomSidebar
Component:- This is a functional React component that defines the structure and content of your sidebar.
useSelect
: This hook is used to retrieve the current value of your custom meta field (_my_custom_sidebar_text
) from thecore/editor
data store. It re-renders the component if the value changes.useDataDispatch
: This hook provides dispatch functions to modify data in the store. Here,editPost
is used to update the post’s meta attributes.PluginSidebarMoreMenuItem
: This component creates an entry in the “More Tools & Options” menu (the three dots in the top right of the editor). When clicked, it will open yourPluginSidebar
.target
: Must match thename
prop of yourPluginSidebar
.icon
: Uses a Dashicon for the menu item.
PluginSidebar
: This is the main component that renders your custom sidebar panel.name
: A unique identifier for your sidebar.title
: The title displayed at the top of your sidebar.icon
: A Dashicon displayed next to the title in the sidebar header.
PanelBody
: Creates a collapsible panel within your sidebar, useful for organizing settings.TextControl
: A simple input field. Itsvalue
is connected to yourcustomText
state, andonChange
callsupdateCustomText
to save changes to the post meta.
registerPlugin()
:- This function registers your entire custom sidebar as a Gutenberg plugin.
render
: Specifies the React component that will be rendered for your plugin (in this case,MyCustomSidebar
).
- Optional: Auto-opening the Sidebar:
- The commented-out line
wp.data.dispatch('core/edit-post').openGeneralSidebar('my-custom-sidebar-panel');
shows how you could programmatically open your sidebar when the editor loads. However, it’s generally recommended to let the user open it via the icon for a better user experience.
- The commented-out line
How to Use This:
- Create Files:
- Place the PHP code in your active theme’s
functions.php
file, or create a new custom plugin and put it in the main plugin file. - Create a
js
folder inside your theme’s directory (e.g.,wp-content/themes/your-theme/js/
) and save the JavaScript code ascustom-sidebar.js
inside it.
- Place the PHP code in your active theme’s
- Activate: If you created a plugin, activate it. If you added to
functions.php
, it’s active with your theme. - Open Gutenberg Editor: Go to create a new post or page in WordPress.
- Find Your Sidebar:
- Look for the “Settings” gear icon in the top right of the editor. If your sidebar has a distinct icon, it might appear next to it.
- More reliably, click the “…” (More Tools & Options) icon in the top right. Under the “Plugins” section, you should see “My Custom Sidebar”. Clicking this will open your custom panel.
This setup provides a robust way to add custom functionality and settings to the Gutenberg editor without trying to override the core Block Settings, which are fundamental to how blocks function.