To remove a metabox from all post types at once, using a foreach seems like the logical thing to do. However it doesn’t always work and I don’t understand why.

For examlple viewing the “Post” post type the following only removes the trackbacksdiv :

function remove_metabox_from_all_post_types() {
$post_types = get_post_types();
foreach ( $post_types as $post_type )
            remove_meta_box('trackbacksdiv', $post_type, 'normal');
            remove_meta_box('postcustom', $post_type, 'normal');
            remove_meta_box('authordiv', $post_type, 'normal');
            remove_meta_box('postexcerpt', $post_type, 'normal');

}
add_action('admin_menu', 'remove_metabox_from_all_post_types', 999);

While this removes all of them when viewing the “Post” post type:

function remove_metabox_from_all_post_types() {
$post_types = get_post_types();
foreach ( $post_types as $post_type )
            remove_meta_box('trackbacksdiv', 'post', 'normal');
            remove_meta_box('postcustom', 'post', 'normal');
            remove_meta_box('authordiv', 'post', 'normal');
            remove_meta_box('postexcerpt', 'post', 'normal');

}
add_action('admin_menu', 'remove_metabox_from_all_post_types', 999);

I would think that get_post_types is fired after the metaboxes are registered, but that’s the only reason I can guess it’s not working the first way, unless it’s a careless syntax error that I’m not picking up. I tried using the do_metaboxes actions hook as well but it didn’t make a difference.

Any ideas?

2 Answers
2

Remember Apple’s “Goto Fail”?

Similar situation:

Your code actually does this, when indentation is corrected:

 foreach ( $post_types as $post_type )
        remove_meta_box('trackbacksdiv', $post_type, 'normal');

 remove_meta_box('postcustom', $post_type, 'normal');
 remove_meta_box('authordiv', $post_type, 'normal');
 remove_meta_box('postexcerpt', $post_type, 'normal');

So, it should does the job for trackbacksdiv, but not for the rest because the function calls are outside of the foreach and $post_type is not defined.

If you replace $post_type with post it works, because..well, the function arguments are complete.

Wrap your foreach in { } and try it again.

Leave a Reply

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