When you add an action via add_action()
, the variables that are available in the callback function are determined by the specific hook you’re using. The load-post.php
hook does not pass any values through to the callback function.
However, when adding meta boxes the correct hook to use is add_meta_boxes
, and that hook provides 2 values to the callback function $post_type
and $post
.
So if you want to conditionally add a meta box based on the post’s page template you can use this $post
variable with get_page_template_slug()
:
add_action( 'add_meta_boxes', 'prefix_post_metabox_setup', 10, 2 ); // The 2 here is required to get both arguments.
function prefix_post_metabox_setup( $post_type, $post ) {
if ( 'my-template.php' == get_page_template_slug( $post ) ) {
add_meta_box(); // etc.
}
}
Just be aware that this means that your meta boxes won’t appear until after the page/post is saved with the new template. In the block editor (née Gutenberg) this might require a manual refresh.
Also, it’s best practice to prefix your functions with something unique to your project. post_metabox_setup
is too generic a name.