Using Meta Boxes on Plugin Admin Pages
Meta Boxes are boxes that appear on the dashboard and for custom features on edit page/post pages. They can also be used in plugins too. Here’s how to create meta boxes on an admin page that will remember whether you have opened/closed them and the order you have dragged them into.
They are relatively easy to create!
1) Enqueue the scripts that will allow toggling open and closed and the order to be changed. They need to be hooked in at the ‘init’ stage
add_action('init',apmbt_init'); function apmbt_init() { /** * * Initialises js scripts and css * * @author Andy Moyle * @param null * @return * @version 0.1 * */ wp_enqueue_script('common'); wp_enqueue_script('wp-lists'); wp_enqueue_script('postbox'); }
2) Create the page the boxes will appear on
Those classes and ids allow the meta box styling to happen
3) Create functions for each meta_box’s content
4) The meta boxes need nonce fields to allow any open/close toggling and order changes to be saved
5) The meta boxes are then “added” and “done”
add_meta_box( $id, $title, $callback, $post_type); //have as many of these as you want //$id is a unique id for the meta box //$title is the title //$callback is the function with the content //$post_type for our implemntation is the name of the plugin //There are other optional arguments which we aren't using
add_meta_box prepares the meta box and can be placed in your content stream or as in an add_action hook
do_meta_boxes tells wordpress to render the meta box
do_meta_boxes( $page, $context, $object ); //$page is our plugin name //$context is advanced //$object is NULL
6) Lastly we need some jquery to initialise previously saved open/close toggles and order
pluginname is your plugin name that you have used above. Other tutorials used pagenow but it didn’t work for me on custom admin pages in v3.5
Here’s the code bundled up…
Meta Box Tutorial Plugin
You can put anything in here, change the order and even close it WordPress will remember!
You can put anything in here too