I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type.
For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types.
Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type.
I couldn't yet find any way to accomplish that, any ideas?
I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type.
For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types.
Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type.
I couldn't yet find any way to accomplish that, any ideas?
Share Improve this question asked Jan 22, 2019 at 12:48 josiasjosias 1959 bronze badges3 Answers
Reset to default 9I know this question is a few months old by now, but I got around this issue using the following code and thought it might be helpful for others. There might be a better way, but this works:
import ColorSchemeSelect from "./components/color-scheme-select";
import includes from "lodash/includes";
const { select } = wp.data;
const { registerPlugin } = wp.plugins;
const { PluginSidebar } = wp.editPost;
registerPlugin('ahr-sidebar-post-options', {
render() {
const postType = select("core/editor").getCurrentPostType();
if ( !includes(["post", "page"], postType) ) {
return null;
}
return (
<PluginSidebar name="ahr-sidebar-post-options" icon="admin-customizer" title="Color settings">
<div style={{ padding: 16 }}>
<ColorSchemeSelect />
</div>
</PluginSidebar>
);
},
});
In my example I only wanted to show a certain sidebar for posts and pages, so I'm using !includes(["post", "page"], postType)
to test wheter or not the sidebar should be shown. If you only want it for one specific post type you'd just go postType === "my-post-type"
instead.
The solution is to wait until dom is ready before to get the current post type.
If you don't wait, the selector will return null
import domReady from '@wordpress/dom-ready';
import { Component } from '@wordpress/element';
import { select } from '@wordpress/data';
class MySidebarPlugin extends Component {
[...]
}
domReady(() => {
if (select('core/editor').getCurrentPostType() !== 'post') return;
registerPlugin('my-sidebar-plugin', {
icon: 'admin-plugins',
render: MySidebarPlugin,
});
});
To add a sidebar to a custom post type, just add the sidebar after the condition:
class SidebarRender extends Component {
[...]
}
var postType = select("core/editor").getCurrentPostType();
if (postType === "my_post_type")
registerPlugin("my-sidebar", {
icon: "excerpt-view",
render: SidebarRender
});