0

I was looking for a way to attach a custom meta box to the edit screen of a page at a specific template.

I found and tried this here and from my actual point of view this can't work that way. Let me explain why I think so: To determine, whether I'm on a screen using a specific template I need reference the global $post. But since this function to create the meta box is hooked into the admin_init the global $post will not yet exist.

So it has to put out an Error message, doesn't it? After those thoughts I tried to tie my meta_box_init function to edit_post, save_post and such. But the codex says, even they need $post to be set. So how could I achieve my page template specific meta box, really? Is there a clean solution?

9
  • At the very beginning of creating the new post first define a template for it and save as draft.
    – Max Yudin
    Commented Feb 10, 2013 at 11:56
  • But how will that prevent me from getting the messages when NOT actually on such an updated page screen? This does not fix the issue $post is not available at the time when initializing the meta box… Commented Feb 10, 2013 at 12:34
  • Simply check current template after post is saved (as draft or any): global $post; if('your-template.php' == wp_basename( get_page_template() ) {//do metabox stuff here};.
    – Max Yudin
    Commented Feb 10, 2013 at 12:47
  • As I've noticed your mentioned link also has similar condition: if ($template_file == 'home.php').
    – Max Yudin
    Commented Feb 10, 2013 at 12:52
  • Thanks but your new approach ends up telling me "Trying to get property of non-object in …/wp-includes/post-template.php on line 1275". The problem with the approach I linked to is, that this $template_file already requires $post to be set as well. Commented Feb 10, 2013 at 13:28

1 Answer 1

1

As I've already wrote in question comments, at the very beginning of creating the new post or page first choose a template and save as draft. Meta box will appear after save if right template is used.

<?php
add_action( 'add_meta_boxes', 'my_add_meta_box' );
function my_add_meta_box() {
    // get template file name
    $template_basename = wp_basename( get_page_template() );
    // check if right template is used
    if('my-template.php' == $template_basename) {
        add_meta_box(
            'my_metabox',
            __('Metabox name'),
            'my_display_metabox',
            'page',
            'normal',
            'high'
        );
    }
}
function my_display_metabox($post) {
    wp_nonce_field( 'my_metabox', 'my_metabox_noncename' );
    // meta box HTML here
}
1
  • Whew, this got it working finally… Thank you very much! Commented Feb 10, 2013 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.