Skip to content

Instantly share code, notes, and snippets.

@pattihis
Last active December 17, 2022 10:49
Show Gist options
  • Save pattihis/a0a8824b1d2fae6e864ec830bd8c9b37 to your computer and use it in GitHub Desktop.
Save pattihis/a0a8824b1d2fae6e864ec830bd8c9b37 to your computer and use it in GitHub Desktop.
WordPress: Show/Hide custom Metabox in Editor Screen based on page template selected.
<?php
add_action('admin_head', 'metaboxScripts');
function metaboxScripts() {
global $current_screen;
if ('page' != $current_screen->id) return;
echo <<<HTML
<script type="text/javascript">
(function($){
$(window).on('load', function () {
const getPostTemplate = () => wp.data.select('core/editor').getEditedPostAttribute('template');
let postTemplate = getPostTemplate();
wp.data.subscribe(() => {
const newTemplate = getPostTemplate();
if( postTemplate !== newTemplate ) {
if (newTemplate === 'page-custom-template.php' ) {
$('#your_meta_box').show();
} else {
$('#your_meta_box').hide();
}
postTemplate = newTemplate;
}
});
});
})(jQuery);
</script>
HTML;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment