Collapse / Close WordPress MetaBoxes

I recently converted the single NGFB Open Graph plugin settings page to multiple submenu pages in WordPress, and at the same time, wanted to present some of the metaboxes closed — either by default, or force them closed whenever the page was displayed. There are generally two ways to do this, one would be to use the add_filter() function to add the “closed” class to some metaboxes, but this would mean forcing the metabox closed every time the settings page was loaded. A more flexible method is to access the user options table with get_user_option(), check to see if a particular page has some open/closed metaboxes, and then decide if we want to force them closed, or just close them by default — If the user has not clicked a metabox open or closed, then no record for that page will be present (thus we can create an entry with our default closed metaboxes).

There are two preliminary functions to call before we can access the user options. The first thing we need is the “pagehook” (the ID string of the page), which is returned by the WordPress functions when creating a menu or submenu. For example:

Once we have the “pagehook”, we can create one or more metaboxes using the add_meta_box() function. The first argument to add_meta_box() is an ID string of our choosing — In this example, the ID string is based on the “pagehook”, an underscore, and descriptive word. For example:

Now that we have a “pagehook” value, we can look into the user options table and set our defaults for that page, or force those two metaboxe closed.

The following collapse_metaboxes() function assumes the metabox ID (first argument to add_meta_box()) is composed of the “pagehook”, an underscore, and a string passed in the array.