I typically use CSS and jQuery for this type of thing by hooking admin_head
. This should be done client-site as a user has an option to select your template or another one after DOM load. Basically, all you do is check if the value is set for #page_template
and toggle show/hide
if your template is selected or not.
add_action( 'admin_head-post.php', 'metabox_switcher' );
add_action( 'admin_head-post-new.php', 'metabox_switcher' );
function metabox_switcher( $post ){
#Isolate to your specific post type
if( $post->post_type === 'page' ){
#Locate the ID of your metabox with Developer tools
$metabox_selector_id = 'id-of-your-metabox';
echo '
<style type="text/css">
/* Hide your metabox so there is no latency flash of your metabox before being hidden */
#'.$metabox_selector_id.'{display:none;}
</style>
<script type="text/javascript">
jQuery(document).ready(function($){
//You can find this in the value of the Page Template dropdown
var templateName = \'template-folder/file-name.php\';
//Page template in the publishing options
var currentTemplate = $(\'#page_template\');
//Identify your metabox
var metabox = $(\'#'.$metabox_selector_id.'\');
//On DOM ready, check if your page template is selected
if(currentTemplate.val() === templateName){
metabox.show();
}
//Bind a change event to make sure we show or hide the metabox based on user selection of a template
currentTemplate.change(function(e){
if(currentTemplate.val() === templateName){
metabox.show();
}
else{
//You should clear out all metabox values here;
metabox.hide();
}
});
});
</script>
';
}
}