
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 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.
- How To Create A Better Meta Box In WordPress Post Editing Page
- How To Create A Better Meta Box In WordPress (Part 2)
- Meta Box Script Update V3.0
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):
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’)
'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>',
'</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):
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):
As you can see, that works!
Conclusion
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.
Download latest version from project page
If you like it, please buy me a beer!
If you have some opinions or ideas, feel free to share your thoughts in the comments.
- How To Create A Better Meta Box In WordPress Post Editing Page
- How To Create A Better Meta Box In WordPress (Part 2)
- Meta Box Script Update V3.0






109 comments
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.
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?
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).
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
Yeah, this would be grand for 2.9.2+
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']);
}
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?
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.
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.
I ended up using the fix mentioned here: http://www.hashbangcode.com/blog/add-enctype-wordpress-post-and-page-forms-471.html and now uploading works.
Ah, I understand what you mean now. I’ve read the link you gave, it’s good :). I’ll update the script. Thanks.
Just updated the script in Part 2.
Awesome! It works perfect.
I only miss a multiple values feature
Ok , I haven seen part 2 :)
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 :)
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!
Regards,
Tiago
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.
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.
Regards,
Tiago
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
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?
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?
Just add this code where you want to display the custom field in your theme.
ID, ‘name-of-the-field’, true);?>
It works just like any other custom field on wordpress. Look at the codex for further information. http://codex.wordpress.org/Custom_Fields
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!
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…
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.
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).
Thanks! Exactly what i’m looking for my theme.
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!
The best tutorial for custom meta box i have see on the net! :) Thanks!
How can you add multiple checkboxes using your excellent tutorial?
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
array(
‘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'].”;
}
break;
}
I think the metadata can only hold single values… a metadata key cannot be an array… I don’t think.
YOU
ARE
GREAT
!!!
Excellent, clear, and very useful tutorial — thank you!
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?
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
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.
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?
Does anyone know how to include the specific field items in a template file?
Yes, Sambacine answers that earlier in the comments. (search on Sambacine.)
Hello,
I modified your code a little bit to fit my need, but now i am not able to save all the field value, wp only save the first field
Can You Help Me to solve this code,
http://wordpress.pastebin.com/LqsXQRDb
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.
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.. ;)
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 ?
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 :)
Rilwis
Hello Rilwis,
Thanks a lot for keeping it up and updating the code. I’ve got a question and a suggestion.
Question.
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)?
Suggestion.
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(
array(
‘name’ => ‘Rich editor’,
‘id’ => $prefix . ‘wysiwyg’,
‘type’ => ‘wysiwyg’, // WYSIWYG editor
‘std’ => ‘Default value 2′
),
array(
‘name’ => ‘File upload’,
‘desc’ => ‘For file upload’,
‘id’ => $prefix . ‘file’,
‘type’ => ‘file’ // file upload
),
array(
‘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,
Dasha
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!
very nice
People if you want some more information for creating meta box could reffer to this url
http://techwithketan.wordpress.com/2011/02/09/adding-metabox-in-post/
I love you!!!!!!!
I just wonder that how we add drop down box for multiple values?
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.
You are the men. You just awesome.
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?
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?
Please try the newest version of this script here.
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.
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!
Hi,
Thanks for the report. I’ll fix it in next version of the script :)
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?
Hi, please read this post, I’ve described how to get meta values:
http://www.deluxeblogtips.com/2011/03/meta-box-script-update-v30.html
Sorry for being a dumb ass. I got it now. Thanks.
How do you make it so the checkbox loads with checked=”checked” on by default?
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.
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.
Hello Lindsay,
Actually, your question was answered in this comment. This is a nice trick :)
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
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.
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.
So once I have done this how do I output the information in a page?
Thanks for sharing =) It’s really helpful!!
The explanation and example in the Codex made my eyes glaze over, this was much easier to follow. Thanks.
The explanation and example in the Codex made my eyes glaze over, this was much easier to follow. Thanks.
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).
Thanks, this saved me a lot of reading :) Check your paypal and enjoy the beer ;)
Hi, very useful info here. But I come across one warning when I implement this code:
Warning: call_user_func_array() [function.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?
Hi, it’s work, thanks
Q: how to using custom fields to define the category?
I’m getting a: HTTP Error 500.0 – Internal Server Error :(
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!
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.
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.
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. :)
That’s a good idea. I’ll do that in the next version.
Absolutely brilliant! I’m using your code for my wordpress website with custom posts and works like a charm :) thank you!!!
me too but how can i display my content on the website?
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.
me too – getting nothing with 3.2.1
Sorry, this works good. Problem was I had some leftover functions trying another aproach.
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']);
}
}
There’s a mistake in my code:
bones_show_box should be mytheme_show_box according to your code :-)
great! it works in dashboard!
now, how can i display the meta box content on the website?
thanks!
Please go to the project page to see the full documentation!
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
I was struggling with adding custom meta for a a few days. Your post helped me. Thank you for sharing!
[...] custom fields to it using a Meta Box. There are lots go articles that outline how to do it, I referenced this one quite a bit and found it very helpful. In my instance, the Meta Box that holds all of the custom [...]
[...] excellent tutorial for creating meta boxes, also including file and image upload can be found in this article on DeluxeBlogTips.An excellent class that simplifies the creation of metaboxes is WPAlchemy Metabox.Another plugin [...]
Using this method, how would I add another metabox to the same page?
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.
Oh.. thanks for this awesome tutorial! meta box, the easy way to manage custom post, don’t you agree?? :)
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
Thanks heaps for this. How do I then make this display on a page?
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(
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
),
array(
‘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.
I wrote the following code for those using multiple metaboxes http://pasteit.com/16298 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.
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.
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!
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.
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.
I’m not very clear about your idea. Can you explain a bit more?
I have the two metabox fields Address and Map coordinates. I would like to group them under one title “Contact information”. see the pic http://screencast.com/t/PWdden5Gdi