Display Plugin Sidebars and Custom Fields for Specific Page Templates Only

We kind of did the similar thing on my blog, when we restrict displaying <PanelBody> only for specific post types. In this tutorial we are going to do almost the same, but for the condition we take a page template selected for post.

This is an example how it is going to work:

display Gutenberg panels for specific post templates only
So, “Contact page settings” section is visible only if “Contact us” page template is selected.

And here is the code to achieve that:

( function( wp ) {

	const { registerPlugin } = wp.plugins;
	const { PluginDocumentSettingPanel } = wp.editPost;
	const { withSelect } = wp.data;

	const MishaPanel = ( { template } ) => {

		if( 'contact-me.php' !== template ) {
			return null
		}
		
		return (
			<PluginDocumentSettingPanel
				name="misha-panel"
				title="Contact page settings"
			>
				<p>This is going to be displayed only for specific page templates.</p>
			</PluginDocumentSettingPanel>
		)
		
	}

	// we are going to use withSelect in order for template to be available inside
	const MishaPanelwithSelect = withSelect( select => {
		return {
			template: select( 'core/editor' ).getEditedPostAttribute( 'template' )
		};
	} )( MishaPanel );

	registerPlugin( 'misha-panel', { render: MishaPanelwithSelect } );

} )( window.wp );

It is possible to condition <PanelBody> elements, whole plugin sidebars or just specific fields inside it.

You can also add multiple post templates into the condition:

if( ! [ 'page-templates/test.php', 'contact-me.php' ].includes( template ) ) {
	return null
}

In case you are creating plugin sidebars with my plugin Simple Fields, you can pass one or multiple page templates into post_template parameter, below is the code you can insert to your theme functions.php file.

add_filter( 'simple_register_sidebars', function( $sidebars ) {

	$sidebars[] = array(
		'id' => 'misha-test',
		'post_template' => array( 'page-templates/test.php', 'contact-me.php' ),
		'name' => 'Contact page settings',
		'fields' => array(
			array(
				'id' => 'my_text_field',
				'label' => 'Text field',
				'type' => 'text',
			)
		)
	);

	return $sidebars;

} );
Misha Rudrastyh

Misha Rudrastyh

Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.

Need some developer help? Contact me

Follow me on X