remove custom meta boxes not working

what I was trying to do here is to remove some custom fields that I created when a template is selected, aka when I select certain template I want to hide or show specific metaboxes.

The code I have is the following but it isn’t working at all (thats to say that it doesn’t remove any metaboxes) and I would like help to see what’s wrong with it or if what I’m trying to do it’s just not posible.

    add_action('admin_init','my_meta_init');
    function my_meta_init(){
    $template_file = get_post_meta(get_the_ID(), '_wp_page_template', TRUE);

if (($template_file == 'thanks-template.php') || ($template_file == 'view-template.php')) 
{
    remove_meta_box('my_meta_box_id','page','normal'); 
    remove_meta_box('my_meta_box_id_2','page','side'); 
    remove_meta_box('my_meta_box_id_3','page','side');
    remove_meta_box('dynamic_sectionid','page','normal');     
} else
{
    remove_meta_box('my_meta_box_id_4','page','normal'); 
}
    }

Related posts

2 comments

  1. Thanks you for the comments and answer, everyone helped. The problem was on the hook I was using, I changed it and now it’s working perfectly :

      add_action('admin_head','my_meta_init');
    
  2. You may need to change the HOOK you are using to hook in your function.

    That is you need to hook into admin_menu instead of admin_init as the metaboxes might not exist the moment you are trying to remove them. So a certain order is needed to make sure metaboxes removal call is made when actual metaboxes are generated and exist.

    I tested following code on my localhost and it hid the Author div/metabox fine when used this code snippet:

    function remove_page_fields() {
        remove_meta_box( 'authordiv' , 'page' , 'normal' ); //removes author 
    }
    add_action( 'admin_menu' , 'remove_page_fields' );
    

    Another Approach:

    By the way, as I think about the situation you are facing, maybe add the metaboxes/custom fields in such a way, that they are shown only to the pages we are meant to. I have worked on projects where I need to show some metaboxes only when certain template is selected.

    I use CMB2 class to generate metaboxes mostly, if you happen to use that or something similar, you may use this parameter to specify the page templates https://github.com/WebDevStudios/CMB2/wiki/Display-Options#limit-to-specific-page-templates

Comments are closed.