Show or hide meta boxes when changing the WordPress page template

WordPress has had the concept of page templates for a long time, but it was only in the last major release (4.7) that this feature was extended to support all post types. The timing couldn’t have been better, as Growella makes use of custom, named page templates for different types of content (regular articles, “Your Job is Whaat?!?” episodes, and more).

Being able to change the page template being used is great, but often a specialized template requires some specialized post meta to go with it. How can we show or hide different custom meta boxes based on the current template? I’m glad you asked!

Listen for changing page templates

This little bit of JavaScript, injected into the admin area via the admin_enqueue_scripts action, lets us toggle the visibility of different meta boxes based on the currently-selected page template.

var pageTemplate = document.getElementById( 'page_template' ),
 someMetaBox = document.getElementById( 'my-custom-meta-box' ),

  /**
   * Toggle the visibility of different meta boxes, based on the current page template.
   *
   * @param {string} template - The ID of the current post/page template.
   */
  setActiveTemplate = function ( template ) {
    if ( 'templates/my-template.php' === template ) {
      someMetaBox.removeAttribute( 'hidden' );

    } else {
      someMetaBox.setAttribute( 'hidden', true );
    }
   },

   /**
    * Read the current template selection and call setActiveTemplate() for it.
    */
   changeTemplate = function () {
     setActiveTemplate( pageTemplate.options[ pageTemplate.selectedIndex ].value );
   };

/**
 * Listen for changes to the post/page template.
 */
pageTemplate.addEventListener( 'change', changeTemplate );
changeTemplate();

This bit of code does two things: first, it listens for changes on the #page_template element (the select menu). When a change is detected, it gets the input value and calls setActiveTemplate(), which toggles the visibility of meta boxes (via the hidden attribute) depending on which template is selected.

Hopefully this approach will be useful for you when customizing the WordPress post edit screen, as it certainly has been for us!

Leave a Reply