
Learning how to create custom WordPress meta boxes allow you to make professional UI elements for yourself and your clients. This WordPress meta box tutorial will show you how to add admin UI elements to the edit post/page screens.
Important Before you begin reading, you might want to read Take Your WordPress Meta Box to the Next Level. This PHP class will let you create meta boxes fast with the flexibility you need as a developer. Full documentation walks you step-by-step. Create custom WordPress Meta Box UI elements for your projects with ease.
Creating a custom WordPress meta box lets you make clean UI elements for you and your clients. The default WordPress custom fields are functional, but IMHO, and if you can pull it off, using a WordPress meta box is the way to go. It will give your project that professional touch.
This WordPress meta box tutorial will show you how to quickly add a clean UI for some custom fields. You will even learn how you can hide these fields and prevent them from appearing in the custom fields area.
Getting Started with WordPress Meta Boxes
The code for your meta box will pretty much go in one of two places: in a plugin file or in your functions.php file. This tutorial will cover the latter (for those of you creating plugins, you will be able to adapt the code for your use as well). I like tutorials with code examples and lots of comments, with that said, lets dive right in:
I recommend that you download the sample files or cut + paste the code and markup below in the appropriate places as indicated. There are three sample files (you will also need to create a folder and name it custom):
/current_theme_folder/functions.php /current_theme_folder/custom/meta.php /current_theme_folder/custom/meta.css
/current_theme_folder/functions.php file:
<?php
define('MY_WORDPRESS_FOLDER',$_SERVER['DOCUMENT_ROOT']);
define('MY_THEME_FOLDER',str_replace("\\",'/',dirname(__FILE__)));
define('MY_THEME_PATH','/' . substr(MY_THEME_FOLDER,stripos(MY_THEME_FOLDER,'wp-content')));
add_action('admin_init','my_meta_init');
function my_meta_init()
{
// review the function reference for parameter details
// http://codex.wordpress.org/Function_Reference/wp_enqueue_script
// http://codex.wordpress.org/Function_Reference/wp_enqueue_style
//wp_enqueue_script('my_meta_js', MY_THEME_PATH . '/custom/meta.js', array('jquery'));
wp_enqueue_style('my_meta_css', MY_THEME_PATH . '/custom/meta.css');
// review the function reference for parameter details
// http://codex.wordpress.org/Function_Reference/add_meta_box
// add a meta box for each of the wordpress page types: posts and pages
foreach (array('post','page') as $type)
{
add_meta_box('my_all_meta', 'My Custom Meta Box', 'my_meta_setup', $type, 'normal', 'high');
}
// add a callback function to save any data a user enters in
add_action('save_post','my_meta_save');
}
function my_meta_setup()
{
global $post;
// using an underscore, prevents the meta variable
// from showing up in the custom fields section
$meta = get_post_meta($post->ID,'_my_meta',TRUE);
// instead of writing HTML here, lets do an include
include(MY_THEME_FOLDER . '/custom/meta.php');
// create a custom nonce for submit verification later
echo '<input type="hidden" name="my_meta_noncename" value="' . wp_create_nonce(__FILE__) . '" />';
}
function my_meta_save($post_id)
{
// authentication checks
// make sure data came from our meta box
if (!wp_verify_nonce($_POST['my_meta_noncename'],__FILE__)) return $post_id;
// check user permissions
if ($_POST['post_type'] == 'page')
{
if (!current_user_can('edit_page', $post_id)) return $post_id;
}
else
{
if (!current_user_can('edit_post', $post_id)) return $post_id;
}
// authentication passed, save data
// var types
// single: _my_meta[var]
// array: _my_meta[var][]
// grouped array: _my_meta[var_group][0][var_1], _my_meta[var_group][0][var_2]
$current_data = get_post_meta($post_id, '_my_meta', TRUE);
$new_data = $_POST['_my_meta'];
my_meta_clean($new_data);
if ($current_data)
{
if (is_null($new_data)) delete_post_meta($post_id,'_my_meta');
else update_post_meta($post_id,'_my_meta',$new_data);
}
elseif (!is_null($new_data))
{
add_post_meta($post_id,'_my_meta',$new_data,TRUE);
}
return $post_id;
}
function my_meta_clean(&$arr)
{
if (is_array($arr))
{
foreach ($arr as $i => $v)
{
if (is_array($arr[$i]))
{
my_meta_clean($arr[$i]);
if (!count($arr[$i]))
{
unset($arr[$i]);
}
}
else
{
if (trim($arr[$i]) == '')
{
unset($arr[$i]);
}
}
}
if (!count($arr))
{
$arr = NULL;
}
}
}
?>
/current_theme_folder/custom/meta.php file:
<div class="my_meta_control"> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras orci lorem, bibendum in pharetra ac, luctus ut mauris. Phasellus dapibus elit et justo malesuada eget <code>functions.php</code>.</p> <label>Name</label> <p> <input type="text" name="_my_meta[name]" value="<?php if(!empty($meta['name'])) echo $meta['name']; ?>"/> <span>Enter in a name</span> </p> <label>Description <span>(optional)</span></label> <p> <textarea name="_my_meta[description]" rows="3"><?php if(!empty($meta['description'])) echo $meta['description']; ?></textarea> <span>Enter in a description</span> </p> </div>
/current_theme_folder/custom/meta.css file:
.my_meta_control .description
{ display:none; }
.my_meta_control label
{ display:block; font-weight:bold; margin:6px; margin-bottom:0; margin-top:12px; }
.my_meta_control label span
{ display:inline; font-weight:normal; }
.my_meta_control span
{ color:#999; display:block; }
.my_meta_control textarea, .my_meta_control input[type='text']
{ margin-bottom:3px; width:99%; }
.my_meta_control h4
{ color:#999; font-size:1em; margin:15px 6px; text-transform:uppercase; }
If you’ve set everything up correctly you should see the following meta box in a edit post or edit page screen:

Using The Meta Box Values In Your Template
Being able to create the values is just the first part, now you need to do something with those values. Most likely you will be displaying the values in your post or page templates.
Remember the example above uses a single variable (_my_meta) to store values as an array, so when you get the meta value back from WordPress it will be an array and you will have to access the values using array syntax. Doing this is pretty straight forward:
$my_meta = get_post_meta($post->ID,'_my_meta',TRUE); echo $my_meta['name']; echo $my_meta['description'];
The global $post variable should always be available, but here are some other methods you can use to get the current post or page ID which you will need to use with get_post_meta():
// using $post global variable
echo $post->ID;
// get a page by its path (recommended over using a page ID)
$page = get_page_by_path('company/contact-us');
echo $page->ID;
// if you are working in the loop
echo get_the_ID();
The above code and markup will help you produce clean UI elements for your next WordPress project. Like any tutorial, consider this a starting point for you to do great things. I hope you’ve enjoyed!

how to echo this to my theme function?
To test out the code above, the easiest thing to do is to download the sample files and give it a try, you’ll get the hang for how it works and you will be able to modify it to your liking.
Elegant code and works properly on page or posts, but no luck with Custom Post Types in WP 3.0. Changed
foreach (array('post','page') as $type)toforeach (array('feature') as $type). Then the metaboxes only showed up on that custom post type which is great. But when I enter in the fields text, after clicking save it does not save. Changedif ($_POST['post_type'] == 'page')toif ($_POST['post_type'] == 'feature')as but still no luck. Also tried adding:// check autosavebut still no luck.if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
Desperately trying to figure this out before tomorrow morning, but will stay up all night til I get it. Thanks in advance!
Cheers,
Christopher
Tried installing on the latest version of WP 3.0. Works for Posts but doesn’t seem for custom post types. Changed ==page to == the name of my custom post type. Have it set to only show the boxes on that post type, and everything appears to work but when you enter in data it does not save. Tried adding do not autosave as this article recommends but still no luck. Any ideas anyone? http://osdir.com/ml/wp-testers/2010-03/msg00205.html
Hi,
I have everything set up looking perfect in the add page section of the site, but how do I get the value to show up in my template?
I’m trying: echo get_post_meta($post->ID, ‘_my_meta’ true);
Which echo’s “Array” in my template.
Any guidance would be very much appreciated.
Tom, the the current setup I propose above, does use an array … so as you’ve noticed when you echo an array it outputs “Array” … to inspect the variable you can try:
In your template you would do the following:
Thanks for the comment, I will update the post above with further info to make this how to complete.
Perfect, thanks a lot man!
I’m trying to get the meta data to display and right now it is showing nothing. Data saves and updats in post. When I print_r the results, I get a 1. Any idea what I might be dong wrong.
$arr = get_post_meta($post->ID,'_my_meta',TRUE);echo $arr['link'];
By the way, does it make a difference if I have set up a custom post type (events).
Luke, I assume you are using WordPress 3.0 (beta). I did a test install, setup a custom post, and tested the code above … all seems to work.
I assume you can see the meta box in the post admin area, you probably already updated the following line:
foreach (array('post','page','events') as $type) ...Things to check: make sure you are getting the correct “post_ID”, you might also check the “wp_postmeta” table and confirm that the “_my_meta” key is being set for the post.
Dimas,
Thanks for the reply. I did get this working using WP 3.0 Beta 1 (current version of nightly build). I checked the DB for _my_meta and it was there along with checking the post_ID being correct.
I ended up having to call the
global $post;. So in the events template:global $post;
$arr = get_post_meta($post->ID,'_my_meta',TRUE);
echo $arr['link'];
echo $arr['description'];
Thanks again for the reply. This is by far the cleanest, organized and easiest way I’ve found to accomplish this. I’ve had luck with other methods but again, this is much more friendly way of doing it. Great post!
(I hope this doesn’t submit a numerous amount of times, it didn’t appear to show up initially.)
Dimas,
I’m not sure if you have used Gravity Forms (www.gravityforms.com) before or not. It is the best thing out there for forms and even lets you create a post by submitting the form info into custom posts. I have this working with the exception of it posting the custom fields into the “User Friendly” way you’ve provided in this post. I wanted to pick your brain to see what you might suggest as to what the custom field value may be (4 screenshots below to help)
http://dl.dropbox.com/u/2557221/0-form-setup.png
Gravity Form Setup – This allows the post to submit a custom field. What would I set the custom field value as?
http://dl.dropbox.com/u/2557221/1-form-preview.png
Form Preview – You can see the fields and the values being set.
http://dl.dropbox.com/u/2557221/2-added-to-events.png
It’s been added to “Events” – After submitting, it shows it posted to the Events Custom Posts.
http://dl.dropbox.com/u/2557221/3-custom-fields.png
Custom Fields View – This shows the custom fields being set as shown, although not in the “User Friendly” area you’ve demonstrated here.
Thanks in advance for any thoughts you might have. I really appreciate it!
Hi! Is there a way to show customized meta-boxes UI on each category?
For instance.
Category 1
custom_field 1
custom_field 2
Category 2
custom_field 1
custom_field 3
Luke, as you’ve read with the above tutorial, I find it easier to: use a single variable, submit data via array notation, and save/use an array into the
wp_postmetaDB table.I haven’t used Gravity Forms before, but by looking at your screenshots it appears as if it would be best to enter in the custom field names individually (meaning you would not have one custom field name to store all the data).
Certain parts of the code above would need modification, primarily the
my_meta_setupfunction (to get the individual name/value pairs) and themy_meta_savefunction (to save the individual name/value pairs).Before posting this tutorial I was using a similar setup, where I used one-to-one name/value pairs for my custom fields, but that setup got a little cumbersome for me pretty quickly, so i tried to simplify and that is what you see above.
If you need some samples of my old code I can send it to you, just email me at dimas3 [at] farinspace [dot] com
Christopher, your post got marked as SPAM by Akismet (I apologize for not seeing it sooner), I hope you’ve gotten what you needed working! Let me know otherwise…
Donalyza, I don’t see why you couldn’t have dynamic meta boxes and/or dynamic fields. You could have certain fields be displayed or hidden based off certain post properties, in this case categories:
So, following the tutorial above, in your
/current_theme_folder/custom/meta.phpfile, you could use the following to display certain fields when the post is assigned to certain categories:< ?php if (in_category('category-slug',$post->ID)): ?> HTML < ?php endif; ?>I hope I’ve understood your question correctly and that the above helps you.
Thank you! I was able to make it to work. You just made my day.
Dimas,
Thank you for the reply. Actually, still experiencing the problem. When I follow your instructions for custom meta boxes on WP 3.0 for the normal post type, works perfectly. When I use it for a custom post type I created, all the boxes show up however when I enter in information into a metabox and click save, the content in those boxes disappear. I can post some code, but first is their anything off the top of your head that might cause this, that I should for first? Thanks Dimas!
Chris, I’ve made some modifications to the code above in the
functions.phpfile, so try the latest and see if that works for you…Thanks for the update. I updated to your new code, but it still does allow me to save in the boxes unfortunately. Also with the new code, now when I try to save in a normal post that does not work either. Where is before that did work, and it only didn’t work in custom post types. I have you functions.php code at the end of my own functions file for the site. I pasted the part of the file that relates to the issue: http://pastie.org/949123 If you get a chance maybe you can see where I’m going wrong, or point me in the right direction. To note, on this line foreach (array(‘post’,'work’,'page’) as $type) I only left post and page for testing, but I will ultimetly only wanting the metaboxes to show on the work post type. So foreach (array(‘work’) as $type) Thank you!
Actually, now I’m thinking maybe the problem is in my meta.php file. I created names for each field but now sure if I did it properly. http://pastie.org/949140
I think I’m definitely over quota on posts here today. But I noticed in the meta.php file I uploaded, I misspelled ‘url’ as ‘u’. Fixed that but still no luck. And tried you meta.php unchanged and still no luck on saving. Thanks again in advance. I’ll keep trying different things here to see if anything works. So close!
Chris, I used your Pastie code for
functions.phpandmeta.phpand was able to get it working as expected.Your last variable
_my_meta[url]has a small typo:_my_meta[u]try the following to see where the saving function is failing: http://pastie.org/949174
It’s good to know it’s working for you at least as the problem must lie else where in my code. (where I haven’t been looking!).
I had fixed the typo prior but no luck. check1,check2,check3 all where echoed as well as the rest of the code. http://pastie.org/949220
The last line however said Warning: Cannot modify header information – headers already sent by (output started at /dev/wp-content/themes/mytheme/epanel/custom_functions.php:465) in /dev/wp-includes/pluggable.php on line 887
To note: 465 is echo “check-1″ the start of the function my_meta_save
Does this mean I am using that same function name somewhere else? Your debugging tip certainly is pushing me in the right direction.
Cheers
Now this is odd, so I tried changing the function name: my_meta_save to my_meta_saves in both locations. And it worked! Then I tried putting them both back to my_meta_save and it still works. Even after emptying my cache several times. I have no idea if using the debug script once, or changing the function name once somehow refreshed something or what. So strange, but looks like I’m good now. Thank you for sticking it out with me. If I can figure out exactly what fixed the issue I’ll be sure to post for other readers.
Now that I have been able to save meta box data successfully due to the dedicated help of Dimas I needed to figure out how to display the inputs in the template. The code above by Luke worked perfectly in WP 3.0b2. Everything is finally working as it should.