Wordpress - Make Custom Metaboxes Collapse by Default

To display a metabox collapsed or closed by default, it is good to know that adding closed to it's class attribute will display it closed. All meta-boxes main divs that have closed in their classname, are displayed in the closed form.

When the arrow is clicked it will be removed or added (toggled). This is done interactively on the post editor page. Manually adding the closed classname does only work if you do that in your browser with a developer tool like firebug or similar.

As Wordpress normally tracks the status of the toggle state of each metabox, you should take care to only initially set the toggle state to close the first time a specific user is visiting the editor or is added to users.

The data which of those metaboxes are closed is stored inside the users options, each time you toggle a box, there will be an ajax request that is storing it:

update_user_option($user->ID, "closedpostboxes_$page", $closed, true);

$closed is a comma-seperated list of all metaboxes IDs that are closed. $page is set to "post" for the post editor (the one you asked for). So when a new user is created (or the plugin is installed for all existing users), you can extend that setting with the ID of your metabox. This should do the job.

The only thing you need to know is the ID of your metabox, but I'm pretty sure you know that one already. If not, check your code where you register the metabox.

Additionally, next to the ones that are closed, you can also set those which are hidden btw, which would correspond to the checkboxes. It's the hiddenpostboxes_$page option then.

Update

Some code snipped on how to add the option:

function collapseBoxForUser($userId, $page, $boxId) {
    $optionName = "closedpostboxes_$page";
    $close = get_user_option($optionName, $userId);
    $closeIds = explode(',', $close);
    $closeIds[] = $boxId;
    $closeIds = array_unique($clodeIds); // remove duplicate Ids
    $close = implode(',', $closeIds);
    update_user_option($userId, $optionName, $close);
}

just call that function with the proper values and it will insert your boxId into the value. Next time the editor is loading that value for the screen (e.g. via an ajax request), it should display that box closed.


Another way to do this is to use the hook in get_user_option:

function closed_meta_boxes( $closed ) {
    if ( false === $closed )
        $closed = array( 'submitdiv', 'postcustom', 'anothermetaboxid' );

    return $closed;
}
add_filter( 'get_user_option_closedpostboxes_{post_type_slug}', 'closed_meta_boxes' );