Skip to content

Instantly share code, notes, and snippets.

@Luehrsen
Created June 26, 2023 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Luehrsen/15c0c7e485a971c321d601da34189b81 to your computer and use it in GitHub Desktop.
Save Luehrsen/15c0c7e485a971c321d601da34189b81 to your computer and use it in GitHub Desktop.
WordPress Block Editor: How to avoid switching to the block sidebar when a block is selected.
/**
* We want to open the document sidebar when the block is selected.
* We want this behavior for our meta block, as all relevant settings
* are in the document sidebar. The block sidebar is useless, empty and
* distracting.
*/
/**
* Import dispatch function from the core/edit-post store.
*/
const { openGeneralSidebar } = useDispatch('core/edit-post');
/**
* Get the current active general sidebar name and the editor sidebar state.
* We need to check if the editor sidebar is opened, because we don't want
* to open the document sidebar when the editor sidebar is closed.
* We also need to check if the block sidebar is opened, because we don't
* want to spam the editor with sidebar changes if it is already opened.
*/
const { getActiveGeneralSidebarName, isEditorSidebarOpened } = useSelect(
(select) => {
return {
getActiveGeneralSidebarName:
select('core/edit-post').getActiveGeneralSidebarName,
isEditorSidebarOpened:
select('core/edit-post').isEditorSidebarOpened,
};
}
);
/**
* Use an effect to open the document sidebar when the block is selected.
* We need to check if the block is selected, because this effect will also
* run when the block is deselected. We don't want to open the document
* sidebar when the block is deselected.
* We also need to check if the block sidebar is opened, because we don't
* want to spam the editor with sidebar changes if it is already opened.
* We also need to check if the document sidebar is already opened, because
* we don't want to spam the editor with sidebar changes if it is already
* opened.
*/
useEffect(() => {
/**
* Get the name of the current active general sidebar and compare it
* to the block sidebar name.
*/
const blockSidebarOpened =
getActiveGeneralSidebarName() === 'edit-post/block';
/**
* If this block is selected AND the block sidebar is active AND the
* editor sidebar is opened in general, open the document sidebar.
*/
if (isSelected && blockSidebarOpened && isEditorSidebarOpened()) {
openGeneralSidebar('edit-post/document');
}
}, [
isSelected,
openGeneralSidebar,
getActiveGeneralSidebarName,
isEditorSidebarOpened,
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment