Adding a custom meta box in WordPress

Written by Keith on the 4th May, 2011. Filed under: Tips & Tricks, WordPress

In this little tutorial, we will be creating a simple meta box in WordPress that will be displayed when we are writing a new post. The meta box we will create is very basic and will only print some text but this will get you comfortable with using them.

First off, open up your functions.php file and add the following code.

add_action('add_meta_boxes', 'eirestudio_create_meta_box');
function eirestudio_create_meta_box()
{
   add_meta_box('eirestudio_meta_wrapper', 'My Super Meta Box', 'eirestudio_display_meta_box', 'post', 'side' ,'default', '');
}

function eirestudio_display_meta_box()
{
   echo 'Eire Studio welcomes you!';
}

Heres how it works

The add_action function attaches a custom function (which we have to create) to an action; the action we are using in this tutorial is the add_meta_boxes action. The add_action function accepts 4 parameters:

  • tag (required) - The name of the action you wish to hook onto. A list of available actions are here.
  • function_to_add (required) - This is name of your function you want to be used.
  • priority - This determines when your function is called in relation to other functions. The default setting is 10.
  • accepted_args - How many arguments your function takes.

The eirestudio_create_meta_box function is a function we will use to create the meta box by using the add_meta_box action. The add_meta_box action defines the meta box such as the heading, where it will be shown on the page etc. The add_meta_box action accepts 7 parameters:

  • id (required) = The CSS id that your meta box will be wrapped in.
  • title (required) = The heading of your meta box.
  • callback (required) = The function name to be called to actually show the meta box.
  • page (required) = What screen will this meta box be shown on. Post, page, custom post type or link.
  • context = Which part of the screen will the meta box be shown.
    • normal
    • advanced
    • side
  • priority = The priority in which your meta box should be shown. high, core, default or low.
  • callback_args = Arguments to pass into your callback function.

Then we simply create the eirestudio_display_meta_box function and pop in some content :)