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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | <?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | .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 that 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:
1 2 3 | $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():
1 2 3 4 5 6 7 8 9 | // 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!
Related posts
- How to Keep the Custom Fields Area Uncluttered When Using WordPress Meta Boxes
- Take Your WordPress Meta Box to the Next Level
- How to Limit the Display of a WordPress Meta Box
{ 57 comments… read them below or add one }
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.
Dimas,
Thanks for the reply and advise.
What you said makes perfect sense of why I wouldn’t be able to set valued pairs. Also, as you mentioned, the setup other ways is very cumbersome. Since then, I’ve managed to build a pretty nice Events Custom Post page (thanks to your code) to replace using Gravity Forms. Still use GForms in many other ways.
I appreciate your willingness to offer up your old sample code.
The problem seems to be back. That is I was adding several new posts in my custom post type each were letting me save to the new meta boxes, then all of the sudden the next one I created it stopped working. Didn’t change any code. Tried emptying browser cache, restarting etc. It’s so odd. I will try running your debug script above even though that technically shouldn’t fix it, but did last time some how. Very odd.
Figured out the issue. When I create a new post it works, I was editing posts I had already created prior to whatever change I made to the code that resolved it. (maybe the misspelling of the “url”. Thanks again!
Dimas,
What would be a good way to add multiple meta boxes (e.g. Required Info, Optional Info)?
I’ve done this with your script by adding a second custom.php called
custom2.php. It’s the same script I just had to change some function names and nonce name (e.g.my_meta_inittomy_meta_init2).I played a bit with adding another
add_meta_boxand including the othercustom2.php. I’ll mess around more later but I thought I would get your thoughts if possible on how to possibly reference onecustom.phpfile and have the ability to add multiple meta boxes by including different files undermy_meta_setup(or some other function).This works great! Thanks for sharing. I am trying to implement the conditions on the meta.php file. Do you have an idea what condition I’d use to limit the meta boxes to pages of a certain template?
Normally I’d use if_is_pagetemplate(‘template.php’) but the admin page itself is not actually using the template in question. Maybe I need to pull the meta data in the template field and use that?
Kathy, in your
my_meta_initfunction you can try the following:$post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ; $template_file = get_post_meta($post_id,'_wp_page_template',TRUE); if ($template_file == 'home.php') { ... }or in your
meta.phpfile you can try the following (note that the$postvar is available in themeta.phpfile):$template_file = get_post_meta($post->ID,'_wp_page_template',TRUE); if ($template_file == 'home.php') { ... }Adding the condition to the my_meta_init function worked great. Thanks again!
btw- have you seen this tut: http://www.deluxeblogtips.com/2010/05/howto-meta-box-wordpress.html
your 2 tuts have helps immensely on this subject.
Great, I’m glade it worked out for you and thanks for the link.
Similar to that tutorial, my next update to this series of meta box articles will include a easy helper class for creating one or many meta boxes.
In the latest nightly build they have changed how cutom post types are registered which I am told will break current 3.0 versions.
http://wpdevel.wordpress.com/2010/05/13/earlier-this-week-nikolay-committed-a-c/
Could you do follow up code on how to make your code work with the updated version of 3.0? I’ll also try taking a stab on it on my own tonight.
Chris, thanks for the info. I’ve updated my local dev version of wordpress and all still seems to work OK.
Additionally, I’ve developed a helper class for creating meta boxes, see: Take Your WordPress Meta Box to the Next Level
Excellent, thanks. You da man. =)
Thanks so much for a brilliant tutorial!!! I’ve followed it to the letter and got it all working… only the text fields in the admin area are only 170px wide and I can’t fathom out how to make them wider!!!!
I’ve created the path…
wp_enqueue_style('my_meta_css', wp-folder/theme folder . '/custom/meta.css');perhaps I’ve completely messed this up? I’ve tried alternative paths without success!
Louisa
@Louisa, If you haven’t already checked out my latest code WPAlchemy_MetaBox do take a look, it improves upon this tutorial tremendously …
as for your CSS you may want to try something like this:
if (is_admin()) wp_enqueue_style('custom_meta_css',TEMPLATEPATH . '/custom/meta.css');TEMPLATEPATHis a wordpress constant (remember it as it is a useful one) …Thanks for the super fast reply!!! I used the WPAlchemy_MetaBox code and it’s brilliant! Everything works perfectly! Thank you so much!
Thanks again!!!
Louisa
Hello again!!!!! Sorry to ask another question!!!
What’s the best way to add images using the WPAlchemy meta boxes?
I’m adding this file path…
to meta.php
ImageOne
<input type="text" name="the_name(‘imageOne’); ?>” value=”the_value(‘imageOne’); ?>”/>
Add the first image here
and to my post_template.php
the_value(‘imageOne’);?>
I’m getting the image in my meta boxes which is fine but it’s a little difficult to delete!
Thanks!!!!!
Oh, the above didn’t quite come out properly! Sorry! Hope this makes more sense!
Included in single_template
the_value('imageOne');?>
Included in meta.php
Top Image
<input type="text" name="the_name('imageOne'); ?>" value="the_value('imageOne'); ?>"/>
Add image one here
The image code added to the custom meta box
@Louisa, my recommendation for letting users add images is to direct users to use the default wordpress media upload feature. In the meta box you then basically ask to a URL of the image.
I personally find that this helps the end user get familiar with the default features of wordpress and how they work.
However, there may be cases where you want to create an “upload” form field and have a user select a file to upload. In these cases you will need to modify the “save” function to handle the uploaded file (put it in the correct directory and such).
Thanks Dimas!!!! I was doing something really really weird before which is why I mentioned the image being difficult to delete!!
Adding sections of information into Wordpress is now so much easier!
Thanks again!
Hello! It’s Louisa again! Sorry to pester AGAIN but I was wondering if it’s at all possible to have a wysiwug html/visual editor field right bang smack in the middle of the meta boxes rather than being perched on top of the page?
For example… say I want list the meta boxes like so
1. “add heading here” meta box
2. “add introduction here” meta box
3. “add image here” meta box
4. THEN have the wysiwug html/visual editor field here.
5 .”add another image here” meta box
Thanks!!
Hope you have a brilliant weekend!
Louisa, great question, you’ve inspired me to write an article about it:
How to Move and Position The WordPress WYSIWYG Visual Editor
And it’s an absolutely brilliant article!!! Thanks!!!!!!
Louisa
Hi mate,
Congrats on the work! Let me ask you a question, is it possible to control where add_meta_box will fire?
For example, I have a category called Events and another one called News, I have an events area created with magic fields and a plugin.
I want a certain metabox to appear only on the Events (new and edit) posts.
If you could clarify anything to me I will be very pleased.
Thanks a lot Dimas
Eduardo, Be sure to check out my WordPress Meta Box PHP class, there is a filtering section which will let you filter by categories.
Dimas:
Great tutorial!
I was wondering if you could give me some tips on how to have a rich text editor on textareas inside the metabox. Maybe extending the built-in tinyMce that already appears on the default editor?
Dimas,
Great tutorial! With the data being serialized in the database, is there anyway to delete a single value from the array? I tried using wordpress’ delete_post_meta function, but I’m officially stumped! thanks for any help/guidance!
Tyler
Tyler, as you’ve already noticed, the code uses an array to store its data. The
my_meta_clean()function will clean that array when items are deleted (are emptied). For instance: when you clear the data from a form field the array will be cleaned.I am going to be working on a new version of the WordPress Meta Box PHP class which will allow the developer to choose how the data is stored, via an array or via the classic WordPress name/value scheme.
You need to add
add_action('edit_post','my_meta_save');to themy_meta_initfunction. That will save changes.Keep in mind that
edit_postaction gets fired on post/page edit and on comment add/edit … here is what WordPress says aboutedit_post:“Runs when a post or page is updated/edited, including when a comment is added or updated”
I believe the
save_posthook is the correct action to use in this case.That’s EXACTLY what I’m after… thanks so much
This is just awesome! I created a custom post type but I also wanted to have specific information included and I searched and searched and couldn’t find anything that worked. Until your tutorial! Works perfectly! Thank you very much!
One thing though I took out the wp_enque_style for the meta.css as it wasn’t working and just did a link to the style sheet in the meta.php file. Works like a charm.
Also to Christopher B – A big thanks to you as well – u ran into some issues I was having i.e. defining the post type and after reading all your comments (lol) i got it to work. Nicely done.
Hey Dimas,
In what way is it possible to import meta data using CSV format?
I took a look at the SQL backend and saw that it makes an array in the meta field and I am not sure of a plugin that could do something like that.
I do recall a CSV importer but I dont believe it does meta data..
Noel, I think the default WordPress export/import functionality will work with
wp_postmetadata as well.If you were to write a plugin to do this, it shouldn’t be too hard either, you basically would have to select * from a table and write it as a CSV file with PHP. Unfortunately I don’t know of anything that would do this easily for WordPress.
If you can’t find anything ready available you mighty be able to do it with phpMyAdmin as a data export, additionally I use Navicat for MySQL and it has options to export MySQL tables as CSV and the like.