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.

meta-box

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

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 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

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…


5 Comments on “Using Meta Boxes on Plugin Admin Pages”

  • Gavin Simpson May 28th, 2015 8:00 pm

    Very nicely done.

    Thank you for the effort, it is much appreciated.

  • shaka October 2nd, 2016 3:27 pm

    hi
    you saved my tons of hour.
    i m searching for 2 days.
    thank you so much

  • Brian January 13th, 2017 3:49 am

    I don’t understand why we need this code (on line 73):

    $(“.if-js-closed”).removeClass(“if-js-closed”).addClass(“closed”)

    It doesn’t seem to make a difference on the behavior of the page. Without it, metaboxes are still rendered in their previously open/closed state. Can you explain the downside to omitting this snippet of code?

  • Andy Moyle January 13th, 2017 7:21 am

    If I remember rightly it’s to do with if you have set the box closed in screen options.

  • Barrett Golding October 18th, 2018 8:07 pm

    Thanks for this, a real time-saver. I made one change so scripts load only on specific settings page (replacing the ‘init’ add_action and its callback):

Leave a Reply