How To Create A Better Meta Box In WordPress Post Editing Page

How To Create A Better Meta Box In WordPress Post Editing Page

Update: The script was turned into Meta Box WordPress plugin and is being developed. Visit plugin page to see more info and download latest version.

WordPress is one of the most powerful blog platforms out there. One of its strength is the ability to allow post authors to assign custom fields to a post. This arbitrary extra information is known as meta-data and can be added using the Custom Fields box under the content editor of writing post screen. The problem is that adding these meta data handy is not a good idea for most users because they have to know what are the meta key and type of its value. It’s better when developers create a custom meta box that can show which information is needed and give some explanations to users. In this tutorial, we’ll see how to creating a better meta box in WordPress post editing page.

Before we start, make sure that you theme has functions.php file. All of our code will be pasted into this file. And our result will be like this (click to enlarge):

Custom meta box

Step 1. Define meta box with all needed fields

Open the functions.php file, and put the following code into it:

$prefix = 'dbt_'; $meta_box = array( 'id' => 'my-meta-box', 'title' => 'Custom meta box', 'page' => 'post', 'context' => 'normal', 'priority' => 'high', 'fields' => array( array( 'name' => 'Text box', 'desc' => 'Enter something here', 'id' => $prefix . 'text', 'type' => 'text', 'std' => 'Default value 1' ), array( 'name' => 'Textarea', 'desc' => 'Enter big text here', 'id' => $prefix . 'textarea', 'type' => 'textarea', 'std' => 'Default value 2' ), array( 'name' => 'Select box', 'id' => $prefix . 'select', 'type' => 'select', 'options' => array('Option 1', 'Option 2', 'Option 3') ), array( 'name' => 'Radio', 'id' => $prefix . 'radio', 'type' => 'radio', 'options' => array( array('name' => 'Name 1', 'value' => 'Value 1'), array('name' => 'Name 2', 'value' => 'Value 2') ) ), array( 'name' => 'Checkbox', 'id' => $prefix . 'checkbox', 'type' => 'checkbox' ) ) );

Let me explain the code:

In the beginning of the code, we defined a prefix:

$prefix = 'dbt_';

This prefix will be added before all of our custom fields. Using prefix can prevent us from conflicting with other scritps that also use custom fields.

The next variable $meta_box will hold all information about our meta box and all custom fields we need. Let’s look at the first lines:

$meta_box = array( 'id' => 'my-meta-box-1', 'title' => 'Custom meta box', 'page' => 'post', 'context' => 'normal', 'priority' => 'high',

These are meta box’s attributes:

  • id: just the ID of meta box, each meta box has an unique ID
  • title: the meta box title
  • page: The type of Write screen on which to show the meta box (‘post’, ‘page’, or ‘link’) (for WP 3.0, see note below)
  • context: The part of the page where the meta box should be shown (‘normal’, ‘advanced’ or (since 2.7) ‘side’)
  • priority: The priority within the context where the boxes should show (‘high’ or ‘low’)

For WordPress 3.0: If you’re using custom post type in WordPress 3.0 (for example you created new post type 'album'), you can change the 'page' attribute to 'album' to show the meta box in the editing screen of 'album' only.

Below are custom fields. Each custom field has the following attributes:

  • name: The name of the custom field, it will be shown to user.
  • desc: A short description explaining what it is to the user.
  • id: the id of the field, prefixed by the $prefix. It will be used to store the custom field value
  • type: the input type: select, text, textarea, radio or checkbox
  • options: used to declare an array of options for a some type of input (select, radio)
  • std: the default value of the custom field.

Step 2. Add meta box to Edit Page

To add a meta box to edit page, we hook to admin_menu action as in the following code:

add_action('admin_menu', 'mytheme_add_box'); // Add meta box function mytheme_add_box() { global $meta_box; add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']); }

The function is used to add a meta box to edit page is add_meta_box. This function has 6 parameters:

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

Each parameter has the same meaning as the meta box’s attribute (I’ve explained it before), except the $callback parameter. The $callback parameter is the name of callback function, used to display HTML code of custom fields. In our situation, this function is mytheme_show_box.

Step 3. Show meta box

We need to implement the callback function mytheme_show_box to show HTML code of all custom fields. The function looks like:

// Callback function to show fields in meta box function mytheme_show_box() { global $meta_box, $post; // Use nonce for verification echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />'; echo '<table class="form-table">'; foreach ($meta_box['fields'] as $field) { // get current post meta data $meta = get_post_meta($post->ID, $field['id'], true); echo '<tr>', '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>', '<td>'; switch ($field['type']) { case 'text': echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc']; break; case 'textarea': echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc']; break; case 'select': echo '<select name="', $field['id'], '" id="', $field['id'], '">'; foreach ($field['options'] as $option) { echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>'; } echo '</select>'; break; case 'radio': foreach ($field['options'] as $option) { echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name']; } break; case 'checkbox': echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />'; break; } echo '</td><td>', '</td></tr>'; } echo '</table>'; }

It is a large function, isn’t it? But it’s not very hard to understand.

In the very first of the function, we create a hidden field to store a nonce number. It’s required to verify this came from the our screen and with proper authorization:

echo '<input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

And then we display all custom fields in a table. Using the PHP foreach loop, each field is displayed based on its type. Before displaying the custom field’s value for select, radio and checkbox input types, we need to check the “saved” value (if it already exists) and compare to the default values. This is done via the line code:

// get current post meta data $meta = get_post_meta($post->ID, $field['id'], true);

The HTML code of each custom fields is just input fields with some attributes like id, name, value, etc.

After this is done, we’ll get the meta box on Editing Page like this (click to enlarge):

Custom WordPress meta box

Step 4. Save meta data when post is edited

To save the data of custom fields, we need to hook to save_post action:

add_action('save_post', 'mytheme_save_data'); // Save data from meta box function mytheme_save_data($post_id) { global $meta_box; // verify nonce if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // check permissions if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($meta_box['fields'] as $field) { $old = get_post_meta($post_id, $field['id'], true); $new = $_POST[$field['id']]; if ($new && $new != $old) { update_post_meta($post_id, $field['id'], $new); } elseif ('' == $new && $old) { delete_post_meta($post_id, $field['id'], $old); } } }

In the beginning of the function, we check the nonce to make sure that the data is come from edit post with proper authorization.

And then, we check the autosave feature. We don’t want to save the data automatically via autosave feature. We want to save the data only when use clicked on the button Save (or Publish). If you really want to save the data via autosave feature, you can delete these lines (don’t worry, they don’t affect to the rest of code).

// check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; }

The last check is the user capability. We just check if user can edit post or page.

After all of verifications, we use the foreach loop to walk through every custom fields. If the custom fields is not in the database or it is changed, we update it (note: the update_post_meta also adds post meta when the meta is not present in database). If the custom fields is empty, we delete it from database.

When the post is edited or published, we can check the keys and values of custom fields as in the following screenshot (click to enlarge):

Custom meta box for WordPress

As you can see, that works!

Enjoy meta box script for WordPress

Using custom meta box is a great way to make custom fields more friendly to users. It helps us much to add extra information to a post. I hope this tutorial is helpful for you to easier implement a custom meta box in WordPress. I have made a file with all necessary code that you can include in your functions.php file. All you need to change (to fit your requirements) is only the prefix and meta box declaration at the very top of code.

If you have some opinions or ideas, feel free to share your thoughts in the comments.

This post is the first part of meta box series:

For those who speaks Belorussian, enjoy translated version of meta box tutorial by Bohdan Zograf.


  1. This is the best explanation of creating custom meta boxes I’ve seen. I really appreciate that you demonstrate the use of select, check box and radio. The individual descriptions for each item are also very help. Thanks for writing this.

  2. Great write. I’m currently using the More Fields plugin (which is freaking fantastic by the way). However, I have a number of websites I need to roll out, so having to manually add and configure every field via More Fields for every website is just not an option.

    Would your implementation work for pre-existing fields? I have one website already set up with 50+ posts and around 10 custom fields for each. Would I just ignore all the prefix instances?

    1. Yes, you can leave the $prefix as blank to use your existing fields’ names. Just remember to set the ID to correct value (the actual field’s name).

  3. I have been trying to achieve this for days by following advice from other bloggers. Then I found this article and got it working in ten minutes. Thanks

    1. for multiple post types:

      ‘page’ => array(‘post’, ‘page’),

      foreach ($meta_box[‘page’] as $page_type){
      add_meta_box($meta_box[‘id’], $meta_box[‘title’], ‘show_featured_settings_box’, $page_type, $meta_box[‘context’], $meta_box[‘priority’]);

  4. This is a great utility/plugin. How do you get by the ‘enctype=”multipart/form-data’ requirement for the tag for files and image uploads?

    1. I don’t understand your question much. This is just must-have attribute of upload form, so I put it here to make it works.

    2. Uploading an image/file won’t work if the actual form doesn’t have the enctype set. It just returns an empty array for $_FILES and nothing gets uploaded.

    3. Ah, I understand what you mean now. I’ve read the link you gave, it’s good :). I’ll update the script. Thanks.

  5. A fantastic tutorial, and it works just perfectly with 3.0.

    Thanks for having the most readable tutorial that I could find on this topic. You’re my hero for the day 🙂

  6. Hi,

    Really cool function, works very nice. I just have one question: how can I create a delete buttom for the image upload, in case I need to remove the imagem from the post?

    Thank you very much for all this great information and help!


    1. I haven’t created the delete button yet, but in case you want to delete images, you can use the default uploader (manager) of WordPress. And the custom field for images can be deleted using Custom Fields traditional box.

      If you want to insert another image, just upload another image, the old image will be replaced.

    2. Rilwis, thank you very much for the reply. I´m trying to replace flutter to construct a cms like experience for the cliente. And I´m finding it hard to do with just the new wordpress 3 features.

      For instance, when I create a custom post type in Flutter, it can be in one category automatically. I didn´t found a way to do that with a function. The same for the delete button.

      After a lot of research, I came to conclusion that the best alternative is to do a button who changes the content of the custom field image from whatever to empty. That way, the field would be deleted.

      I´m aware of the possibility to delete the field, but it would be nice to have it implemented like flutter. Anyway, sorry for venting. Thank you very much for all the information, it´s really working very well.


    3. Rilwis thank you so much for the great Plugin(Tutorial). Its really worth a lot an safes me putting together several plugins which still can not achieve all this.
      Finally I still want to join Sambacine Produções’s request for a clearing-button for files or images.
      If its not too complicated to explaine i would be very thankful for an advice.
      thanks A LOT

    4. The old image does not replace. Is there a way to add a delete button to delete the file from hard drive and the url in meta?

  7. Please forgive the newbie question, but once you add the fields and save the data, how do you get the new custom fields to display when a visitor is viewing the content? Doesn’t WordPress know to display the fields that you created?

    1. Thanks Sambacine for answering the newbie question.

      This tutorial seems incomplete without some mention of how to display the new meta fields. You completed it – and everything works like a charm. Thanks!

    2. sorry, but i dont understand it here, you posted:

      ID, ‘name-of-the-field’, true);?>

      so.. what is this for a function? get_post_meta, get_post_custom…?

      it works by me with get_post_meta, but i can manage to get it to work with get_post_custom… and it wold be better wit _post_custom or? cos if i have 20 of post, in each one 10 custom metas, and i want to display it all on one page, that would be with get_post_meta about 200 database querys or…? with get_post_custom only one?

      Or i’m i getting it wrong? I’m a begginer, so sorry for the stupid questions, but im googlen it now for few hours and can’t find the right answer…

  8. Hi there – firstly, excellent tutorial, and I am quite pleased with your thorough explanation. Hoping someone here may have run into this issue while implementing. IF I delete or overwrite your 5 arrays (text box, text area, checkbox, select box, radio), and replace with my own, for some reason, wordpress does not show the entry boxes, checkboxes, etc for my new fields. BUT if I place those 5 arrays back into the code along with my new fields, they all show fine. Unfortunately, I do not need your 5 arrays but cannot seem to get around this quite unusual issue. Any thoughts or guidance???? Thank you.

    1. Please check the code first, and read the article again carefully for explanation. This code works well for almost cases. 5 arrays are just the examples, we can change into anything (I’ve tested myself).

  9. Rilwis, this is a great tutorial, thanks so much! I noticed you wrote this in April and I’m just curious if any of it can be simplified now that 3.0 has been officially released. Maybe a dumb question, but just curious. Thanks!

  10. I’ve tried adding multiple checkboxes with this code, but it’s not saving my values correctly. This is some of my code in functions.php

    ‘name’ => ‘Sesong’,
    ‘id’ => $prefix . ‘sesong’,
    ‘type’ => ‘checkbox’,
    ‘options’ => array(
    array(‘name’ => ‘2009/2010’, ‘value’ == ‘checked’),
    array(‘name’ => ‘2010/2010’, ‘value’ == ‘checked’)

    function _show_box() {

    foreach ($meta_box[‘fields’] as $field) {

    case ‘checkbox’:
    foreach ($field[‘options’] as $option) {
    echo ”, $option[‘name’].”;

    1. I think the metadata can only hold single values… a metadata key cannot be an array… I don’t think.

  11. How can you prevent WordPress from showing those custom fields in other post types? If I create a custom post type called films for example, and I have custom meta boxes here, and I store them as custom fields. Now if I go to add a new post, the keys of those custom fields are pre-filled out in the custom fields section. Any way to prevent that?

  12. Hello,
    The Custom fields get as name the ID of the field, instead of the NAME of the field. How to solve this? The new field gets the name prefix-id, but it just has to be the NAME. Please help

    1. To clearify what I need: I need to be able to put a space in the custom field name. Now, as soon as i put a space in the id (inside tha array), the whole thing is broken. But I can make a custom field manually with spaces in the custom field name. So, how to make a the correct custom name WITH spaces, by using this function.

  13. Firstly thank you so much for this excellent tutorial, I’m using it now on lots of my sites and it works a treat. I have one small problem, a new site I’m making has a custom post type which requires a lot of images uploading via custom fields, but for some reason wordpress only seems to upload some of the images, it seems like it can’t upload too many at a time or something, have you encountered this at all?

  14. Great tutorial – thanks! Made setting up this new site so easy. I’ve got 2 select boxes populated from a different custom post type each, and its making data management so much more robust.

    Do you know any good sources of info on implementing jQuery/JSON with your code? I want to display a select box with contents dependent on the selection from another select box.

  15. Please… Can somebody help me?I really like this code and I am trying using it in my site.So.. I am having a problem: We have the save() function, that save all fields from Meta Boxes created by this script… And I have other function running on transition post status… to send an email for me and change one of the fields from my post. (custom field meta box)I think that two functions are in conflict.. because when transition status (from pending to publish)… my custom field DON’T change!!!! Please, It’s is a serious problem for me… I need some help ….Thanks in advance!Miriam de Paula.PS: Sorry my poor english.. I am from Brazil and I don’t speak english.. 😉

  16. Does anyone know how make it so you can ‘add new’ like the default custom field does ?

    so I can have this functionality for my own custom fields ?

    make sense ?

    1. This script only helps you to create a predefined meta box easily. All the
      fields of meta box must be defined before using. So “add new” button is not
      included in this script.

      But you can still have your own custom fields by defining your meta box by
      your needs. Just no Ajax Add new button 🙂


  17. Hello Rilwis,

    Thanks a lot for keeping it up and updating the code. I’ve got a question and a suggestion.

    I have multiple metaboxes that appear on different custom-post-types (CPT) pages. Say metabox 1, 2 appear on CPT-1 page and metabox 3 appears on CPT-2 page. However, when I save a post of CPT-1 type the data from all 3 metaboxes are saved under that post id in the wp_postmeta table. Ideally, only data from metaboxes 1, 2 that actually appear on the CPT-1 page will be saved for the corresponding post it. Hope that makes sense. Is there a way to do that in function save($post_id)?

    At the moment data saved separately for every field in a metabox in the wp_postmeta table. However, sometimes it’s better to have 1 record in wp_postmeta for the whole metabox. Will it be possible to extend the code to do it? So, for example we declare a metabox the following way:

    // second meta box
    $meta_boxes[] = array(
    ‘id’ => ‘my-meta-box-2’,
    ‘title’ => ‘Custom meta box 2’,
    ‘pages’ => array(‘post’, ‘film’, ‘album’), // custom post types, since WordPress 3.0
    ‘context’ => ‘normal’,
    ‘priority’ => ‘high’,
    ‘key’ => ‘my-meta-box-2-data’, // store all the data from this metabox under a single key in the wp_postmeta table
    ‘fields’ => array(
    ‘name’ => ‘Rich editor’,
    ‘id’ => $prefix . ‘wysiwyg’,
    ‘type’ => ‘wysiwyg’, // WYSIWYG editor
    ‘std’ => ‘Default value 2’
    ‘name’ => ‘File upload’,
    ‘desc’ => ‘For file upload’,
    ‘id’ => $prefix . ‘file’,
    ‘type’ => ‘file’ // file upload
    ‘name’ => ‘Image upload’,
    ‘desc’ => ‘For image upload’,
    ‘id’ => $prefix . ‘image’,
    ‘type’ => ‘image’ // image upload


    I have extended the code for your file version 2.2. to cope with a single key for the whole metabox. Please let me know if you would like to have a look at it and I will email that to you ( not sure my extra code super smart as I’m only a newbie 🙂

    Many thanks,

  18. Hey thank you for the guide! quiet usefull.

    For those who dont want to blow up you functions.php, you also can easy write a plugin based on that code here.

    By the way there is a little error in the code of “Step 3. Show meta box”.
    The last ” echo ”, ” in the sixth last line have to be a closed tag or you get some validation errors.

    Thank you for the guide anyway, helped a lot!
    greating from Germany!

    1. Currently, the script doesn’t accept multiple values in a dropdown box. But don’t worry, I’m working on this and will release a new version soon.

  19. I having city list in drop down menu, and want to select multiple selection of cities and add to DB. Could you please let us know how that would be possible?

  20. Thanks a lot!

    I just need different textareas (sizes and alignments) in the Backend. For example: a two-column layout with a large textarea on the left and a small on the right. The best way it seems would be variables for the different fields, but all I’ve tried out doesn’t work.

    Any idea?

  21. This seems pretty cool….I wish I would have stumbled across this before I learned how to do it all the hard way…of course…that’s the way it always works.

  22. I keep getting this notice in the debug section only when I add a new post. It goes away after I publish the new post.

    Notice: Undefined index: post_type in meta-box.php on line 439

    Am I doing something wrong? How do I correct this? I’m just starting to get my head around these massive updates since the first version. Great work!

    1. Cool. And how do I get the second, thrid, etc. file when I use the Uploaded files feature ?
      If the first one is: rw_code, then what is the second? rw_code_2?

    1. Hi Jamie,

      To check if checkbox is checked, I take the value from post meta fields, if
      it’s set, so the checkbox is checked, otherwise not checked.

      You should download the code and look into it how I implemented.

  23. Thank you so much for the extensive tutorial.. I have all of the answers I need to work on this except for one.

    I want to only trigger these meta boxes if a particular page “template” is chosen. For instance on my home page I will have three separate text areas – I don’t want widgets because its stilly – they will always be text areas and will never need any other widget.

    I would love to be able to add the content into three meta boxes on the home page edit screen but I can’t figure out how to display them if a page template is chosen.

  24. Thank you, i was really in the need of this for a project, its great to let the user insert more information to specific areas

  25. This is the best worpdress function i have seen. I’m not sufficient enough with PHP to do it myself.

    I did spot something weird and did not see any mention of it in the comments. When you create a custom post type, exclude the editor and include your image upload function the lightbox is not working. It does show the gray overlay, but is not showing the upload/edit box.

    I think it has something to do WordPress not loading the html for the lightbox (so there is nothing to see) when the editor is disabled. Currently i resolved this by adding display:none to the editor div.

    Maybe i am not using the right solution for this problem, but it works for me (and my clients) and had to share it with other users of your function.

    1. You’re right! The code doesn’t load needed js,css separately for these fields. It uses the ones loaded by editor field. And when there’s no editor, the problem occurs. I’ll fix this in next version.

  26. The explanation and example in the Codex made my eyes glaze over, this was much easier to follow. Thanks.

  27. The explanation and example in the Codex made my eyes glaze over, this was much easier to follow. Thanks.

  28. This is fantastic! The only trouble I had was that the color picker was conflicting with WordPress’ built-in load of farbtastic and causing some knock-on problems with anything else that wanted to use jQuery. I’m sure somebody knows the correct way to overcome this but as I’m not using any color pickers I simply commented out the jQuery script echo in meta-box.php (lines 249 – 265).

  29.  Thanks, this saved me a lot of reading 🙂 Check your paypal and enjoy the beer 😉

  30. Hi, very useful info here. But I come across one warning when I implement this code:

    Warning: call_user_func_array() []: First argument is expected to be a valid callback, ‘add_review_metaboxes’ was given in /yyy/zzz/public_html/domain/wp-includes/plugin.php on line 395

    #wpadminbar { display:none; }

    Any idea what that can be?

  31. I love this script, it’s ingenious and it saves me sooo much time! I just donated you a beer earlier. There is just one thing, I can’t get the time picker to work. The box opens up fine, but the sliders won’t work. I’m on WordPress 3.2.1. Do you know if there’s anything to be done about this? Cheers!

  32. The info in this post is very good, but I will never tell anyone to come here. I will not tweet about it, share it on facebook or subscribe to your rss feed. When I arrived here, not just one but two advertisements started playing loudly. When I finally got one of them to stop, while I was searching the page for the other, a second ad started playing in the first ad box. Plus, firefox informed me that this site is trying to redirect me to another page. It’s a real shame. There is much on this site worth reading and you do a good job of presenting it. But I would never send anyone here because of the intrusive ads and the unknown destination of the redirect. Sorry.

    1. I’m really sorry about that. I haven’t known the ads are playing loudly. I’ve just removed them and replaced with normal Google Ads. Sorry again.

  33. Thank you so much for such a useful script! It’s made my life a lot easier, and I’ve used it to build several plugins. One thing however – storing dates in human-readable format in the custom fields means that you can’t easily sort your query by it. The actual value stored should be strtotime($custom_field_value) when the data is saved – and then converted back to a date for display on the metabox.  This would allow people to sort by the field very easily, just by adding two conditions to the query, as opposed to writing a mysql query. 🙂

  34. Absolutely brilliant! I’m using your code for my wordpress website with custom posts and works like a charm 🙂 thank you!!!

  35. Well it sounds like others have this working, but for me, my wordpress 3.2 admin area blanks to a white page with nothing in it.

  36. Hi,

    it works really good. But I missed one little thing: To use a the meta box in multiple pages.
    So, if you use the following function for adding the meta box, you can assign $meta_box a string [i.e. ‘post’] or an array [i.e. array(‘post’, ‘page’)]:

    // Add meta box
    function mytheme_add_box() {
    global $meta_box;

    if (is_array($meta_box[‘page’])) {
    for ($i = 0; $i < sizeof($meta_box['page']); $i++) {
    add_meta_box($meta_box['id'], $meta_box['title'], 'bones_show_box', $meta_box['page'][$i], $meta_box['context'], $meta_box['priority']);

    } else {
    add_meta_box($meta_box['id'], $meta_box['title'], 'bones_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);

  37. great! it works in dashboard!
    now, how can i display the meta box content on the website?


    1. thanks i got it. just a little problem. i set up two checkbox but on post i see only “on”. how can i display the selected label? thanks again

  38. I was struggling with adding custom meta for a a few days. Your post helped me. Thank you for sharing!

    1. Please see the meta-box-usage.php (if you’re using version 3.2.2) or demo/demo.php (if you’re using version 4.0). There’s an example with multiple meta boxes on the same page.

  39. Oh.. thanks for this awesome tutorial! meta box, the easy way to manage custom post, don’t you agree?? 🙂

  40. This is what i look for a month ago, very easy tutorial to build meta box for wordpress, now it’s easy for me to manage my post page

  41. Howdy, I’m working on a site wherein the previous developer used your approach. It’s awesome. But I have a question.

    I have a case where there is meta data being fed by another source via an API. I need the ability to alter that value and enter it into the DB as meta data.

    So, – I have this in the meta-box-usage.php:

    $prefix = ‘jrlol_’;

    $meta_boxes[] = array(
    ‘id’ => ‘video_meta’, // meta box id, unique per meta box
    ‘title’ => ‘Video Information’, // meta box title
    ‘pages’ => array(‘videos’), // post types, accept custom post types as well, default is array(‘post’); optional
    ‘context’ => ‘normal’, // where the meta box appear: normal (default), advanced, side; optional
    ‘priority’ => ‘high’, // order of meta box: high (default), low; optional

    ‘fields’ => array(
    ‘name’ => ‘Plays Total’, // field name
    ‘desc’ => ”, // field description, optional
    ‘id’ => $prefix . ‘plays_count’, // field id, i.e. the meta key
    ‘type’ => ‘text’, // text box
    ‘std’ => ”, // default value, optional
    ‘style’ => ‘width: 100px’, // custom style for field, added in v3.1
    ‘validate_func’ => ‘check_name’ // validate function, created below, inside RW_Meta_Box_Validate class
    ‘name’ => ‘Play Count Adjustment’, // field name
    ‘desc’ => ‘i.e. enter the number that the Views should be’, // field description, optional
    ‘id’ => $prefix . ‘plays_count_adj’, // field id, i.e. the meta key
    ‘type’ => ‘text’, // text box
    ‘std’ => ”, // default value, optional
    ‘style’ => ‘width: 100px’, // custom style for field, added in v3.1
    ‘validate_func’ => ‘check_name’ // validate function, created below, inside RW_Meta_Box_Validate class

    What I need is a third meta value sent to the DB that adds the two meta values above. I’d like to display it in the meta box if possible but not completely necessary.
    I need this value in the DB because I have queries in which I need to sort the posts by total of the two values.
    I hope this makes sense.
    Just to reiterate:
    $jrlol_plays_count is data fed by outside source via API.
    $jrlol_plays_count_adjustment is data entered by client on post write/edit screen
    I need the above values added and entered into the DB as $jrlol_plays_count_total for use elsewhere on the site to display and as sort value in queries.

    Any help is greatly appreciated.

  42. I wrote the following code for those using multiple metaboxes This is useful if you’re using multiple metaboxes and want to echo your custom fields below their corresponding metabox title. Feedback and suggestions are welcomed.

  43. I have created a post meta box for my site. It is working fine on the local testing site. Unfortunately, when I upload it to the website, it is not working fully. The meta box shows up fine. But when it is time to save, it doesn’t bring me back to the post.

    The url when editing is …../post.php?post…..
    then when saving, it tries to bring me back to: ……/post.php…..
    no ? and then what should follow it.

    Any help would be appreciated, I am a complete noob when working with php.

    1. Ok, I fixed it. It was an simple error on my part in the code in the functions.php file. I was attempting to wrap the code you used here in its own containers. By simply putting it in the current containers (and deleting the new containers) I wasn’t having issues anymore (at least for now). #completenoob THANKS FOR THE TUTORIAL!

  44. Howdy I am so grateful I found your blog page, I really found you by error, while I was researching on Yahoo for something else, Regardless I am here now and would just like to say thank you for a fantastic post and a all round enjoyable blog (I also love the theme/design), I don’t have time to browse it all at the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the great work.

  45. It would be realy nice, if there would be type like Metabox group title ‘type’ => ‘title’,. Return would be value of name
    Then we could group metaboxes easy.

  46. Hallo

    first thnx for this cool post.

    One question i have a meta box with type select ‘Yes’ ‘No’ ‘Text’

    i want to get if i select Text it have to show me a textarea or text so thet i can add cusomize test ther is it possibel??

    1. Yes, you can add this functionality, but it’s all about the custom Javascript work. If you familiar jQuery, I think it’s not too hard for you.

    2. Thnx for ur answer i am not to good in jquery but i will try it.

      If u know Metabox + jQuery howto. let me know.

  47. What a great tutorial, thank you!

    I have a question: You explain how to set a default value for most field types using “std”. Is it possible to set a default value for a Select list? I am having trouble with this.


  48. Hi Rilwis.
    Nice plugin, congratulations. I’m using it over 3 projects still in development but working nice so far.

    I’m also here cause I’m getting Warning messages when editing a meta box registered for a PAGE.

    Warning: Cannot modify header information – headers already sent by (output started at /home/officeco/public_html/_wp/wp-content/themes/officecomm_theme/_includes/officecomm_meta_boxes.php:160) in /home/officeco/public_html/_wp/wp-includes/pluggable.php on line 866

    Although I have no header declaration in my script.

    Any thoughts?

    Thanks in advance.

    1. Which version of the plugin are you using? Do you use any other plugins? I believe that this problem relates with other plugins or scripts of your theme, because there’s nothing outputted in my site (with all debug options turned on).

    2. Just found my error.
      I’m using this snippet to register meta box to certain Pages:

      #postdivrich { display: none !important; }

      Printing style tag (to hide main rich text editor) is causing this error, don’t really know why. Need some more hacking to set this feature correctly.

      Thanks for the attention and, once again, congrats for the job. 😉

  49. Hi rilwis
    Fantasic and awesome tuto man 🙂 thxs!!!

    Question plz:
    In my wp project i try to fill some fields with titles page (the_title()) from my blog like this:


    Page :

    have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
    echo ”;
    echo ”;

    // and here i reset post data

    Everything works fine when i want to edit a page but when i try to add a new one, instead of having blank fields (to add a new page) i always have fields (default field and fields of my metabox) filled with the content of my first page
    i try to reset my query with:
    and i still haf the same problem

    when i change my query to this
    $the_query = new WP_Query( ” );
    blank fields rework fine when i try to add a new page

    Any idea?
    (sorry to disturb u)
    Thanks in advance 🙂

    1. It’s ok it work!
      i just use get_post instead of wp_query or query_post.
      it seems that get_post don’t touch the “loop” 🙂

      And once again thank u for all ur incredible articles 🙂

  50. Simply amazing, well explained and clean code.

    Bookmarked this article, i’m sure i’ll have to re-read it when i’m developing my next WP theme.

    Thanks a bunch!

  51. Hi once again, i’ve followed the follow up tutorials and everything works awesome.

    I already customized my wordpress theme meta boxes with this amazing tutorial.

    I do have one question though: How do i assign a certain meta box to a specific page template?

    For example, i created a few meta boxes that only apply to a specific page template i created. It’s useless to show them on ALL pages. It’s not a custom post type so that won’t work as well.

    Thanks a lot!

  52. This is a great post. Thanks so much for the information. Helped me out a hole bunch on a project I’m developing at the moment.

    1. Not sure if anyone else got this notice when saving?
      Notice: Undefined index:

      After some digging around I found it comes from WP trying to validate the checkbox when it is not selected. I found this to fix the problem.
      if(!isset($_POST[$field[‘id’]])) $new = $old;
      $new = $_POST[$field[‘id’]];

  53. I have an issue with meta fields saving when a user presses the preview button, is there a way to check if the user is previewing and not to save?

  54. This is a cool tutorial, it’s what I was looking for. Add custom field, radio, checkbox, select boxes to my WordPress Post.

    How do I print te content in the custom fields in a template?

  55. I tried to call this function on homepage there is showing only array I am confused please help me out

    1. I looked and couldn’t find it. I found how to set the default of the checkbox but not the radio button. Help?


      PS – LOVING this plugin.

    2. It’s the same as setting default value for all other fields. Just use 'std' => 'value' where value is the value in your registered 'value' => 'label'

    3. Anyone testing this – if you have already run and saved the meta box on the page the default radio button won’t show up if you add ‘std’ afterwards. See the meta() method;

      // Use $field[‘std’] only when the meta box hasn’t been saved (i.e. the first time we run)
      $meta = ( !$saved && ” === $meta || array() === $meta ) ? $field[‘std’] : $meta;

      Great plugin by the way, thank you very much.

  56. hello there and thank you for your info – I’ve certainly picked up anything new from right here. I did however expertise a few technical points using this website, since I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my email and can look out for much more of your respective exciting content. Make sure you update this again very soon.

    1. Hi, I’m having problem with server configuration. Not sure why it happens :(. I’ll try to fix it. Thanks for your kind comment!

  57. Hi
    I am making a review website. I want my user to rate the post by using check list.
    I would like to add just check the boxes to this page
    For example:
    Your Experience with HR Dept.
    1. Good
    2. Bad
    3. Average

    Can you just help me to post a code which I can use to get above value through check boxes to my custom field in post editor. I tried your above code. I pasted it in my function.php file. But dont know if it has worked or not.
    It would be a great help from you, if you just help me.

    1. Thanks a rilwis,
      I have install your plugin as directed.
      What code should I add in below form to appear those check box and to get captured in my post’s custom field.
      Here is my form….

      Your Name*:
      Your Email ID*:

      Your Review:

      Company Name*:

      Industry Type:


      Your Designation:

      Working Period:

    2. Hi Nitin, please see the `demo.php` file in the `demo` folder. There’s a full example of how you define your meta box.

  58. Hello, i just installed your great plugin, and works great 🙂 but not on a specific theme, Agentpress 2.0.
    This is a child theme of Genesis, maybe this particular theme it’s not compatible or i have to twea something to make it work smooth like in the other themes?
    Thank you so much

    1. Hi, it should work normally. At DBT, I’m using eleven40, a Genesis child theme without any problem. The plugin uses WP API, not Genesis’s, so no reasons why it doesn’t work. Maybe you should look into the docs again?

  59. Very clearly explained and yes this code is working fine on my post editor. I customized the code according to my requirement and everything is cool. Thanks for writing this awesome tutorial.

  60. I am regular visitor, how are you everybody? This article posted at this website is really good.

  61. naturally like your web site but you have to check the spelling on several of your
    posts. Many of them are rife with spelling problems and I in finding it very bothersome
    to tell the reality then again I will certainly
    come again again.

  62. Hey ! Thank you for instroction “Meta Box”. I build a new blog and need it. One small Problem exist! If you search with the regular search from wp, you dont find the content from custom fields…

    regards from berlin

  63. Hi,
    First of all I am really thankful to you for providing us this excellent tutorial. I was struggling with creating my own custom fileds and custom type post since two days. I had to develop a form as per requirement of my client. I have created one as per the requirement but I made the mistake of creating different metaboxes for different fields. I have managed to make it work anyhow by playing with loops. However, after going through your code, it took mei hardly 30 minutes to achieve the same task. It is really awesome and will help lots other developers.

  64. Hi thanks a lot for this tutorial, it’s awesome.

    Only a thing, does anybody know if there is a way to include tinymce in my textarea custom field?

    Any clue it’ll be more than appreciate.

    I tried already with the new wordpress function wp_editor but it create a new textarea that doesn’t work.
    If i add wp_editor() in the textarea part (line 22 step 3 echo ‘<textarea name="', $field['id'], … ) when i write something in the post and update it doesn't save anything. How can i say to this new textarea to save the text in the same var as in this example ($meta ? $meta : $field['std'])?

    I tried even enqueing tinmce jquery plug in and it looks ok, but then when i save it doesn't process my html tag and i just have a string back like test test.


    1. hi thanks for repling but if i don’t wanna use a plugin? i’m making a template so i’m looking for another solution instead of using a plugin

    2. i found out thanks to the plug in actually i just added

      // Apply filter to wp_editor() settings
      $editor_settings = apply_filters( ‘rwmb_wysiwyg_settings’, array( ‘wpautop’ => TRUE, ‘media_buttons’ => FALSE, ‘editor_class’ => ‘rwmb-wysiwyg’, ), 10, 1 );

      // Use new wp_editor() since WP 3.3
      wp_editor( $meta, $field[‘id’], $editor_settings );

      this code instead of the textarea part, just one thing, maybe somebody know, why even with wpautop TRUE it doesn’t set the p tad before and after my text?


    3. It works like WP editor. You don’t see the P tag before and after your text, neither, right? Instead of trying to show P tag in the backend, you should use wp_autop function on the front end to show the text with P tags.

    4. I don’t understand how to use wp_autop funcion, in my index.php file perhaps? In my case actually it’s even ok if the p tag doesn’t appear, but is there maybe any chance that when i press enter in my wysiwyg field it appear a tag?

      Anyway thanks a lot rilwis, and i looked at your plug in is really cool. I’m not using it now because i would try to make this template, it’s almost my first one, by myself just to understand as much as possible wordpress but in future i think i will use it, much more simple!


    5. i found out for the moment that i have to put the filter ‘the_content’ while i’m saving the metabox, so now it’s putting the p tags, what i want to do now is str_replace (”,”,$mystring); to add br between p… i’ll find out. thanks again!

  65. Awesome tutorial. My only problems are:

    1) The text field won’t save, here’s all my code for it:

    //Create Review Box
    $prefix = ‘dbt_’;

    $meta_box = array(
    ‘id’ => “rate_box”,
    ‘title’ => ‘Reviewers Information’,
    ‘page’ => ‘lucky_number_reviews’,
    ‘context’ => ‘normal’,
    ‘priority’ => ‘high’,
    ‘fields’ => array (
    array (
    ‘name’ => ‘Reviewer Name: ‘,
    ‘desc’ => ‘Enter reviewer name here’,
    ‘id’ => $prefix.”revname”,
    ‘type’ => ‘text’,

    array (
    ‘name’ => ‘Restaurant Rating: ‘,
    ‘id’ => $prefix.’revrating’,
    ‘type’ => ‘select’,
    ‘options’ => array(‘1’, ‘2’, ‘3’, ‘4’, ‘5’)

    add_action(‘admin_menu’, ‘review_add_box’);

    function review_add_box() {
    global $meta_box;

    add_meta_box($meta_box[‘id’], $meta_box[‘title’], ‘review_show_box’ , $meta_box[‘page’], $meta_box[‘context’], $meta_box[‘priority’]);

    function review_show_box() {
    global $meta_box, $post;

    echo ”;

    echo ”;

    foreach ($meta_box[‘fields’] as $field)
    $meta = get_post_meta($post->ID, $field[‘id’],true);

    echo”, ”, $field[‘name’], ”,

    switch ($field[‘type’]) {
    case ‘text’:
    echo ”, ”, $field[‘desc’];

    case ‘select’:
    echo ”;
    foreach ($field[‘options’] as $option)
    echo ”, $option, ”;
    echo ”;

    echo ”,

    echo ”;

    add_action(‘save_post’, ‘review_save_data’);

    function review_save_data($post_id) {
    global $meta_box;

    if(!wp_verify_nonce($_POST[‘review_meta_box_nonce’], basename(__FILE__)))
    return $post_id;

    return $post_id;

    if(‘page’ == $_POST[‘post_type’])
    if(!current_user_can(‘edit_page’, $post_id))
    return $post_id;
    if(!current_user_can(‘edit_post’, $post_id))
    return $post_id;

    foreach ($meta_box[‘fields’] as $field)
    $old = get_post_meta($post_id, $field[‘id’], true);
    $new = $_POST[$field[‘id’]];

    if($new && $new != $old)
    update_post_meta($post_id, $field[‘id’], $new);
    if(” == $new && $old)
    delete_post_meta($post_id, $field[‘id’], $old);

    2) How do you call it on the template page?

  66. Dear Sir,
    Please help in in my case.

    I want to add a field in front end – like on every post i want to add a check post and if need that check box value in Admin side custome fields.

    1. You can use something like to echo the checkbox: <input type="checkbox" value="1" <?php checked( rwmb_meta( 'field_id' ) ); ?>>

  67. Thank you for this introduction in meta-boxes. I have just startet learning php and i have activated WP_DEBUG in wpconfig.php as recommended. The result of your script (with activated debug-mode) is “Notice: Undefined variable: post” and “Notice: Trying to get property of non-object”. For better understanding this, can you please add an advice how to solve this?

  68. i like your blog. because your blog is very informative. i get here some fantastic genesis themes tutorial. thanks for shearing all those posts with us.

  69. This is by far the bes tutorial/snippet I´ve seen regarding metaboxes. I´ve been honestly looking for a long time into this but had no luck.

    By using an array and php cases the whole thing becomes so easy!

    Thanks a lot!

  70. Great tut! I’m wondering how can I properly add links to option values in a select type. I have been able to do so by simply adding the a tag within the value, however I have noticed anytime I make a change to the post, that value reverts back to the default value within the admin area. Is there something else that needs to be added or am I doing something wrong? See my current code below. Any insight is greatly appreciated!

    'options' => array(
    'Bangerter Homes' => __('Bangerter Homes')

  71. Hello

    If you like Plugins that are simple and easy to navigate, then the Flip Image is just the thing. I love this plugin!


  72. Hi, it’s work very good, thanks
    but I have a question, how to using custom fields to define the category?

  73. hello dear plz help me……
    how to add the new custom field in wordpress

    my code is now

    ‘name’ => ‘Holiday’,
    ‘singular_name’ => ‘Holiday’,
    ‘add_new’ => ‘Add Holiday’,
    ‘add_new_item’ => ‘Add New Holiday’,
    ‘edit_item’ => ‘Edit Holiday’,
    ‘new_item’ => ‘New Holiday’,
    ‘all_items’ => ‘All Holiday’,
    ‘view_item’ => ‘View Holiday’,
    ‘search_items’ => ‘Search Holiday’,
    ‘not_found’ => ‘No Holiday found’,
    ‘not_found_in_trash’ => ‘No Holiday Found In Trash’,
    ‘parent_item_colon’ => ”,
    ‘menu_name’ => ‘Holiday’
    ‘public’ => true,
    ‘has_archive’ => true,

  74. I’m trying to add wp_dropdown_pages as a select value and cannot get the save function to work. Any help would be really appreciated. Thanks for posting this excellent tutorial:

    $prefix = 'rds_';

    $meta_box = array(
    'id' => 'fp-page-meta-box',
    'title' => 'Featured Classes and Services',
    'page' => 'page',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
    'name' => 'Page 1',
    'id' => $prefix . 'select1',
    'type' => 'select',
    'name' => 'Page 2',
    'id' => $prefix . 'select2',
    'type' => 'select',
    'name' => 'Page 3',
    'id' => $prefix . 'select3',
    'type' => 'select',


    add_action('admin_menu', 'rds_add_box');
    // Add meta box
    function rds_add_box() {
    global $meta_box;
    add_meta_box($meta_box['id'], $meta_box['title'], 'rds_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
    // Callback function to show fields in meta box
    function rds_show_box() {
    global $meta_box, $post;
    // Use nonce for verification
    echo '';
    echo '';
    foreach ($meta_box['fields'] as $field) {
    // get current post meta data
    $meta = get_post_meta($post->ID, $field['id'], true);
    echo '',
    '', $field['name'], '',
    switch ($field['type']) {
    case 'select':
    $dropdown_args = array(
    'name' => $field['name'],
    'id' => $field['id'],
    'selected' => $meta
    echo '',
    echo '';

    add_action('save_post', 'rds_save_data');
    // Save data from meta box
    function rds_save_data($post_id) {
    global $meta_box;
    // verify nonce
    if (!wp_verify_nonce($_POST['rds_meta_box_nonce'], basename(__FILE__))) {
    return $post_id;
    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
    return $post_id;
    // check permissions
    if ('page' == $_POST['post_type']) {
    if (!current_user_can('edit_page', $post_id)) {
    return $post_id;
    } elseif (!current_user_can('edit_post', $post_id)) {
    return $post_id;
    foreach ($meta_box['fields'] as $field) {
    $old = get_post_meta($post_id, $field['id'], true);
    $new = $_POST[$field['id']];
    if ($new && $new != $old) {
    update_post_meta($post_id, $field['id'], $new);
    } elseif ('' == $new && $old) {
    delete_post_meta($post_id, $field['id'], $old);

  75. Nice tutorial, rilwis! Thanks!

    I have a question: is there a way to add a class to meta boxes?
    For example in this case:

    ‘label’ => ‘a name’,
    ‘desc’ => ‘description’,
    ‘id’ => ‘id name’,
    ‘type’ => ‘select’,
    ‘options’ => array(‘Bad’, ‘Good’, ‘Excellent’), // HERE I WANT A CLASS FOR THIS GUYS (to customize them in CSS)
    ‘std’ => ”

    Can you tell me, please, how to do that?

  76. Hi and thank you for a great tutorial. It would be worth to mention that id for the fields needs to be unique in case we want to use let’s say two text fields. So 'id' => $prefix . 'text', is not good enough. Radek

  77. I have a link trasfer script like this:

    function updateCountdown() {
    // 140 is the max message length
    var remaining = 20 – jQuery(‘.form-field’).val().length;
    jQuery(‘.countdown’).text( ‘Még’).text( + remaining + ‘ karaktert írhatsz még.’);
    function soh(cur_item) { document.getElementById(cur_item).style.display=(document.getElementById(cur_item).style.display==’none’)?’block’:’none’; }
    jQuery(document).ready(function($) {
    $.event.special.inputchange = {
    setup: function() {
    var self = this, val;
    $.data(this, ‘timer’, window.setInterval(function() {
    val = self.value;
    if ( $.data( self, ‘cache’) != val ) {
    $.data( self, ‘cache’, val );
    $( self ).trigger( ‘inputchange’ );
    }, 20));
    teardown: function() {
    window.clearInterval( $.data(this, ‘timer’) );
    add: function() {
    $.data(this, ‘cache’, this.value);

    function insertText(elemID, text)
    var elem = document.getElementById(elemID);
    elem.value += text;


    Videó neve amire rá kattintanak


    Link neve amire rá kattintanak: 

              <input type="button" value="Galéria létrehozása" onclick="insertText('content', 'Kép megnyitása keretben’);”>           <input type="button" value="Galéria létrehozása link,név nélkül" onclick="insertText('content', '’);”>
      Imdb link Bing képkereső

    And i pasted this for edit-form-advanced.php inside “”.
    Only problem is some, funcktion not working and some plugin also not working for this code.
    Can you help me,why not working this?

  78. hi , thanks for this tutorial
    i have 3 meta box in my custom post
    i want callback the value of the first meta box in the special location in my theme
    and other meta box too
    please help me , thanks

  79. I followed this tutorial and everything work well (saving, outputting) but I don’t get any change when I try to add some lines of code to the switch statement
    For example: when I delete few ‘cases’ from the ‘switch’ statement no changes taking place… or even when I add new class to an input inside the switch, still I get no changes

    Anyone knows what the problem might be?

  80. I m currently new for developing wordpress.I m trying to add a select box in the right side of the above blog.but dont know how to add.I need a select box which has years to select also month and as soon as any1 selects month the posts of that month should appear.I searching a lot but finding difficult to understand those answers.Can you tell me how to add all these.Also can we do it by without using code.plz plz plz reply.

  81. no doubt its a great tutorial, but i am facing a problem, i want to show the field only on edit post page, but this showing meta box on edit and add pages,
    need help

  82. After creating meta box in our custom post type, Now how to print the values on frontend, please help I am new

  83. thanks for nice plugin, now in my case i am working in a company site which has 4 branches so i made a custom post for branches and i need a tab for each branch ,and all of them have the same meta fields. can any one help me plz?

Comments are closed.