4

I am using the WordPress function add_meta_box() to add my own custom metabox.

So how can I auto close/hide on page open ?

Currently, I just add a CSS class closed to metabox's <div> element via jQuery like so:

HTML : (example)

<div id="my_metabox" class="postbox"></div>

jQuery :

$("#my_metabox.postbox").addClass("closed");

But is there a WordPress function to do this ?

5

Hook into postbox_classes. postbox_classes is the function which will output the classes for the metabox.

apply_filters( "postbox_classes_{$page}_{$id}", $classes )

Your code could look like this:

add_action( 'add_meta_boxes', 'add_my_metabox' );

function add_my_metabox() {
  $id       = 'my-metabox';
  $title    = 'My Metabox';
  $callback = 'my_metabox_content';
  $page     = 'post';

  add_meta_box( $id, $title, $callback, $page );

  add_filter( "postbox_classes_{$page}_{$id}", 'minify_my_metabox' );
}

function my_metabox_content() { ... }


/*
 * $classes is an array
 */
function minify_my_metabox( $classes ) {
  if ( isset( $_POST['my_condition'] ) && 'my_condition' == $_POST['my_condition'] ) {
    array_push( $classes, 'closed' );
  }

  return $classes;
}
2

The toggling of a metaboxes' open/close state is done via JS by WP as well - obviously so, since it happens on the client side in his/her browser.

The script that does this goes by the handle 'postbox' *

That script does the same thing you do manually (adds a closed class to close metaboxes). Also, it checks the state of a metabox via if(e.hasClass("closed")).
Hence your way of setting the default state is totally fine.

* As an aside: i.e. should you ever need this functionality on custom admin pages, that's what needs to be enqueued ( wp_enqueue_scripts( 'postbox' ); )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.