How to set default screen options?

I’d love to be able to hide meta boxes using screen options, instead of removing them or restricting them to user roles, the goal is to just “uncheck” the meta box for the user.

I see how this would be tricky since any code that would make a DB change for a user wouldn’t be allowed to run every time they hit the page because it would just reset. But smarter people than I code the core, so maybe there’s a way. And if there is, I’m dying to know.

Any ideas?

4

You are referring to the metaboxes on the admin post screen right?

For that you don’t need a plugin, just drop the following into your functions.php file.

// add_action('user_register', 'set_user_metaboxes');
add_action('admin_init', 'set_user_metaboxes');
function set_user_metaboxes($user_id=NULL) {

    // These are the metakeys we will need to update
    $meta_key['order'] = 'meta-box-order_post';
    $meta_key['hidden'] = 'metaboxhidden_post';

    // So this can be used without hooking into user_register
    if ( ! $user_id)
        $user_id = get_current_user_id(); 

    // Set the default order if it has not been set yet
    if ( ! get_user_meta( $user_id, $meta_key['order'], true) ) {
        $meta_value = array(
            'side' => 'submitdiv,formatdiv,categorydiv,postimagediv',
            'normal' => 'postexcerpt,tagsdiv-post_tag,postcustom,commentstatusdiv,commentsdiv,trackbacksdiv,slugdiv,authordiv,revisionsdiv',
            'advanced' => '',
        );
        update_user_meta( $user_id, $meta_key['order'], $meta_value );
    }

    // Set the default hiddens if it has not been set yet
    if ( ! get_user_meta( $user_id, $meta_key['hidden'], true) ) {
        $meta_value = array('postcustom','trackbacksdiv','commentstatusdiv','commentsdiv','slugdiv','authordiv','revisionsdiv');
        update_user_meta( $user_id, $meta_key['hidden'], $meta_value );
    }
}

Basically what is happening is that for the currently logged in user, you are changing some saved meta_values in the wp_usermeta table.

There are two ways to use this function, you can either hook into ‘user_register’ or you can hook into ‘admin_init’.

The advantage of using ‘user_register’ is that this function will only fire when a new user is registered (thus lower overhead). However it will not work for users that already exist.

If you want it to work for users that already exist, then hook into ‘admin_init’. The disadvantage of course is that now this function fires every time a user goes to the admin page.

Leave a Comment