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.

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!