Last active
December 17, 2022 10:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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