I would like to programatically remove some meta boxes when a user is editing a specific page in the admin. The page itself is using a template (tpl-about.php). I know I can remove all meta boxes from all pages with this function:

function remove_post_meta_boxes() {
 if(!current_user_can('administrator')) {
  remove_meta_box('tagsdiv-post_tag', 'post', 'normal');
  remove_meta_box('categorydiv', 'post', 'normal');
  remove_meta_box('postimagediv', 'post', 'normal');
  remove_meta_box('authordiv', 'post', 'normal');
  remove_meta_box('postexcerpt', 'post', 'normal');
  remove_meta_box('trackbacksdiv', 'post', 'normal');
  remove_meta_box('commentstatusdiv', 'post', 'normal');
  remove_meta_box('postcustom', 'post', 'normal');
  remove_meta_box('commentstatusdiv', 'post', 'normal');
  remove_meta_box('commentsdiv', 'post', 'normal');
  remove_meta_box('revisionsdiv', 'post', 'normal');
  remove_meta_box('authordiv', 'post', 'normal');
  remove_meta_box('slugdiv', 'post', 'normal');
 }
}
add_action( 'admin_menu', 'remove_post_meta_boxes' );

But I need to do this for a specific page only. So how can I test on what template is being displayed in the admin?

1 Answer
1

Those are 2 different things:

  1. Hide only in one Page
  2. Hide only when Page uses a specific template

Case 1 – in this example the Page ID is 3, but note that the removals are for page and post alike:

add_action( 'admin_menu', 'remove_post_meta_boxes' );

function remove_post_meta_boxes() 
{
    if( isset( $_GET['post'] ) && $_GET['post'] == '3' ) 
    {
        remove_meta_box('tagsdiv-post_tag', 'post', 'normal');
        remove_meta_box('categorydiv', 'post', 'normal');
        remove_meta_box('postimagediv', 'post', 'normal');
        remove_meta_box('authordiv', 'post', 'normal');
        remove_meta_box('authordiv', 'page', 'normal');
        remove_meta_box('postexcerpt', 'post', 'normal');
        remove_meta_box('trackbacksdiv', 'post', 'normal');
        remove_meta_box('commentstatusdiv', 'post', 'normal');
        remove_meta_box('commentstatusdiv', 'page', 'normal');
        remove_meta_box('postcustom', 'post', 'normal');
        remove_meta_box('postcustom', 'page', 'normal');
        remove_meta_box('commentstatusdiv', 'post', 'normal');
        remove_meta_box('commentsdiv', 'post', 'normal');
        remove_meta_box('revisionsdiv', 'post', 'normal');
        remove_meta_box('authordiv', 'post', 'normal');
        remove_meta_box('authordiv', 'page', 'normal');
        remove_meta_box('slugdiv', 'post', 'normal');
        remove_meta_box('slugdiv', 'page', 'normal');
    }
}

Case 2 – is more complex, as it involves real-time listening for changes in the Template dropbox.

This Q&A has a blueprint for doing that: Custom meta box shown when template is chosen

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *