Tutorial: Creating Custom Write Panels in WordPress

Use Custom Write options to easily add any unique data to your post

Function | Create a Custom Write Panel in Wordpress Tutorial

Everyone knows that WordPress is one of the most, if not the most, popular blogging systems on the internet today. With its out of the box features, plugins, and great theming community, its no wonder WordPress has been accepted as today’s standard. However, sometimes you just want to add a little more.

It seems the latest fad to hit the WordPress scene is adding thumbnails into a blog post. This is fairly easy to do with some knowledge of custom fields, but can be a little complicated if your client is new to WordPress, or blogging.

Luckily, WordPress has a solution for us. We are going to use a little something called add_meta_box.

Note: This tutorial requires both knowledge of WordPress, as well as PHP.

I shared a link in a comment that WordPress has a little tutorial for this on their site. However, it is a little incomplete, and leaves a little to be desired. So, let’s get started making our own!

Examples of Usage

To see how you can use custom write panels take a look at these couple of examples, or click the image below.

Custom Write Panel Examples - Turorials

functions.php

Please excuse the indention of the code. The WordPress plugin does not like my tabs. :(

All of the code we are about to add will be put in functions.php. This file is included automatically in the Theme, so anything we put in here can be used throughout the theme.

To make this expandable for the future, we are going to declare all of our information in an array. This way, we can add some information to the array, and it will be automatically added to our Admin Panel.

Information Array


/*
Plugin Name: Custom Write Panel
Plugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpress
Description: Allows custom fields to be added to the WordPress Post Page
Version: 1.0
Author: Spencer
Author URI: http://wefunction.com
/* ----------------------------------------------*/

$new_meta_boxes =
array(

);

Inside of that array, we are going to add more arrays which will hold the information of the new meta box.


$new_meta_boxes =
array(
"image" => array(
"name" => "image",
"std" => "",
"title" => "Image",
"description" => "Using the \"<em>Add an Image</em>\" button, upload an image and paste the URL here.")
);

The array is pretty self explanatory. The first value is the name of field, after that would be a standard value (in this case, it is blank, but this would be useful to store default information), and then the Title of the meta_box, ending with the description.

There are 3 functions that will be the backbone here. Let’s go ahead and declare those now:


function new_meta_boxes() {

}

function create_meta_box() {

}

function save_postdata( $post_id ) {

}

Creating the Fields

Lets work on function new_meta_boxes().

This is the function where we are going to build the actual HTML inputs. We first need declare a few variables as global. We will then be able to access them inside the function. We need to be able to access the $post variable, as well as $new_meta_boxes (our array.)


function new_meta_boxes() {
global $post, $new_meta_boxes;
}

Because all of our information is in an array, we need to loop through it all, and create an input box for each one:


function new_meta_boxes() {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {

}

Next we need to figure out a default value for the inputs. We can do this by checking the get_post_meta WordPress function.


function new_meta_boxes() {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {
$meta_box_value = get_post_meta($post->ID, $meta_box['name'].'_value', true);

if($meta_box_value == "")
$meta_box_value = $meta_box['std'];
}

This is some pretty simple PHP. We define $meta_box_value, and set it equal to get_post_meta. Next, we check to see if our variable == "" (equals nothing) meaning no data has been previously entered. If nothing has been entered, we set the $meta_box_value equal to the std value we defined in the array

Time to start building the inputs. First off, we are going to create a hidden field that we will use to verify the data later on.


echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';

Now we can echo the title of our Custom Input:


echo'<h2>'.$meta_box['title'].'</h2>';

Next our actual input box. This gets the value of $meta_box_value we worked out earlier.


echo'<input type="text" name="'.$meta_box['name'].'_value" value="'.$meta_box_value.'" size="55" /><br />';

Finally, just add our little description we defined in the array


echo'<p><label for="'.$meta_box['name'].'_value">'.$meta_box['description'].'</label></p>';

(All of that is still in our function new_meta_boxes() function.)

Make it Meta!

Our next function, function create_meta_box(), will actually create each of the meta boxes. We are going to be using WordPress’s add_meta_box


function create_meta_box() {
if ( function_exists('add_meta_box') ) {
add_meta_box( 'new-meta-boxes', 'Custom Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );
}
}

if ( function_exists('add_meta_box') ) { is important because this function did not exist in versions of WordPress before version 2.5. You need to on at least version 2.5 before this will work.

From WordPress.org, the function works like this:

<?php add_meta_box('id', 'title', 'callback', 'page', 'context', 'priority'); ?>

callback is the most important. That is calling our function (new_meta_boxes). context decides whether or not this field should display on the “Write > Post” page, or the “Write > Page” page. You can read more about the parameters on the WordPress site

Saving the Data

Now here’s the important part, and the part where WordPress.org is pretty vague. This function will save our data.


function save_postdata( $post_id ) {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {

}
}

This is our function, and we’ve started off with including a few variables. Again, we need to include $post so we have the ID of the WordPress post. Also, we have to include the $new_meta_box array, as we will loop through it again.

This next bit (inside of the foreach loop), will verify that the data we are receiving is genuine.


// Verify
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}

if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}

No we are going to define a variable that will get the data out of our fields.


$data = $_POST[$meta_box['name'].'_value'];

It gets the $_POST data from our fields we created in the previous functions.

Now the last thing to do is to decide what to do with the new data. To keep WordPress from creating a new database entry each time, a few checks need to be made. First, we try and get any information with the same key and post id. If it returns empty, we know this custom field has not been added before. So, lets add it.


if(get_post_meta($post_id, $meta_box['name'].'_value') == "")
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);

Next, we check to see if the new data in the field is different from any old data. If it is, we simply update the field.


elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);

The last thing to do is delete one, if the field is left empty. This will keep our database free of any blank entries.


elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));

Now, to actually make things work, we need to “hook” WordPress. We can do this by using add_action. This simply adds our functions to a specific area of WordPress. In our case, we need to hook the admin_menu, as well as when the post is saved, save_post.


add_action('admin_menu', 'create_meta_box');
add_action('save_post', 'save_postdata');

Our Final Code


/*
Plugin Name: Custom Write Panel
Plugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpress
Description: Allows custom fields to be added to the WordPress Post Page
Version: 1.0
Author: Spencer
Author URI: http://wefunction.com
/* ----------------------------------------------*/

$new_meta_boxes =
array(
"image" => array(
"name" => "image",
"std" => "",
"title" => "Image",
"description" => "Using the \"<em>Add an Image</em>\" button, upload an image and paste the URL here.")
);

function new_meta_boxes() {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {
$meta_box_value = get_post_meta($post-&gt;ID, $meta_box['name'].'_value', true);

if($meta_box_value == "")
$meta_box_value = $meta_box['std'];

echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';

echo'<h2>'.$meta_box['title'].'</h2>';

echo'<input type="text" name="'.$meta_box['name'].'_value" value="'.$meta_box_value.'" size="55" /><br />';

echo'<p><label for="'.$meta_box['name'].'_value">'.$meta_box['description'].'</label></p>';
}
}

function create_meta_box() {
global $theme_name;
if ( function_exists('add_meta_box') ) {
add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );
}
}

function save_postdata( $post_id ) {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {
// Verify
if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}

if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
}

$data = $_POST[$meta_box['name'].'_value'];

if(get_post_meta($post_id, $meta_box['name'].'_value') == "")
add_post_meta($post_id, $meta_box['name'].'_value', $data, true);
elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
update_post_meta($post_id, $meta_box['name'].'_value', $data);
elseif($data == "")
delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
}
}

add_action('admin_menu', 'create_meta_box');
add_action('save_post', 'save_postdata');

Implementation

Now I bet you are wondering “now how the heck do I get information?!” Well, it’s quite simple really. You do it the same way you would for a normal custom field. We’ve been using the function already in the tutorial, get_post_meta().

So, just open up one of your theme files where you want the custom data to appear. First, let’s check to see if there is anything entered for this post. Because if there isn’t, we shouldn’t show anything (in this case, it would result in a broken image.)


<?php
if(get_post_meta($post->ID, "image_value", $single = true) != "") :
?>

Now the actual image:


<img src="<?php echo get_post_meta($post->ID, "image_value", $single = true); ?>" alt="<?php the_title(); ?>" />

And to end our if statement:


<?php
endif;
?>

Conclusion

As you can see, customizing WordPress is not an easy task. However, it pays off in the long run. By streamlining the User-Interface of adding custom data, you can help make your life, as well as your clients life a whole lot easier.

If you have any questions about the code above, or the tutorial in general, please do not hesitate to leave a comment below. I will do my best to help answer any questions that may arise.

Written by Spencer on October 20, 2008

Tags: , , ,

Share This:

155 Comments

  • Zinni said:

    Thanks for the great tutorial, I was eagerly anticipating this!

    My latest post: AIGA, What About the Web Designers?

  • Chris Robinson said:

    great tut! gonna try this out on a current project

  • Creating Custom Write Panels in WordPress — WPCandy — WordPress Themes, Plugins, Tips, and Tricks said:

    [...] Spencer of Function writes a great tutorial on creating custom Write Panels with WordPress. [Link] [...]

  • Andrew said:

    A really comprehensive tutorial. I can see this coming in handy later on.

    Good Job.

    My latest post: Widgets - A call for help

  • Cristi said:

    Really Great tutorial! I think I’ll implement this in my next child theme!

    Regards!

    My latest post: Beginners Guide to installing Wordpress

  • Cosmo Kramer said:

    Thanks for this.

    It does not seem to work for me though. When I visit the admin I see all of the functions.php code at the top of the page and the custom box does not appear.

  • Ryan said:

    Great tutorial, now a awesome follow up would be being able to use custom write panels in the front-end. This way a user can add information without having to go to the backend.

  • Spencer said:

    Thanks everyone. Glad you enjoyed it.

    @Cosmo, add your code to Pastie and I’ll check it out.

    @Ryan, I’m not really sure what you mean. You’ll always have to go into the WordPress admin panel to add the information.

  • Chris Robinson said:

    I’m getting a parse error:

    I’ve added the code to pastie, its line 10 thats causing it, any ideas?

    http://pastie.org/296667

  • mkjones said:

    Amazing, stuff like this is popping up everywhere since the release of 2.5 :)

    And surely it can’t be TOO much of a job to modify your example so that a “select image” button could be added which could automatically feed the URL into the field. Although I’m certainly not brave enough to take the task on!

    @Ryan: You COULD use TDO Mini Forms for your proposal. However, I don’t know how well, if at all, it links in with custom fields.

  • Spencer said:

    @Chris Robinson,

    On line 10, you have a “}”, when it should be a “)”.

  • Spencer said:

    NOTE: Anyone who receives Parse error: syntax error, unexpected '&', please check the following.

    In the new_meta_boxes() function, look for $post-& gt;ID and change it to $post->ID. WordPress automatically changes it in my post.

    Thanks!

  • Chris Robinson said:

    ok cool got it working, thanks for the quick response

    the field shows up in the Write page but when I start adding content to the “Post” area and it try’s to auto save a draft, I get the following error underneath the Save & Publish buttons:

    Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, ’save_postdate’ was given in /Users/robinsonc/Sites/wordpress/wp-includes/plugin.php on line 311

    Warning: Cannot modify header information - headers already sent by (output started at /Users/robinsonc/Sites/wordpress/wp-includes/plugin.php:311) in /Users/robinsonc/Sites/wordpress/wp-includes/classes.php on line 806

    functions.php:
    http://pastie.org/296682

    if i take out the code in functions.php it works as normal

  • Spencer said:

    @Chris Robinson,

    Make sure you don’t have any white space (spaces, tabs, etc) under your final ?> at the end of functions.php

  • Chris Robinson said:

    had one hard return, took it out and I’m still getting the same error?

  • How To Create a Custom WordPress Write Panel : CMS Internet Solutions Inc said:

    [...] A good solution for avoiding a confusing mess of custom fields needed to fill out the content in a complex theme: create a custom WordPress write panel. [...]

  • Spencer said:

    @Chris Robinson,

    Check your function names. ;) save_postdate should be save_postdata as you’ve previously declared that as your function name.

  • Chris Robinson said:

    awesome catch! works perfectly, thanks for all the help and a great tut!

  • Spencer said:

    Great! Glad everything seems to working, and you enjoyed the tutorial. :D

  • Chris Robinson said:

    what would need to be done to add multiple custom fields?

  • Spencer said:

    @Chris,

    All you need to do is add another array to our main $new_meta_boxes array. For example


    $new_meta_boxes =
    array(
    "image" => array(
    "name" => "image",
    "std" => "",
    "title" => "Image",
    "description" => "Using the "Add an Image” button, upload an image and paste the URL here.”),
    “image” => array(
    “name” => “subtitle”,
    “std” => “Standard Post Subtitle.”,
    “title” => “Subtitle”,
    “description” => “Add a subtitle to the post..”)
    );

    So basically you can just copy and paste the first one you added, but you need to add a “,” to separate the two.

  • Chris Robinson said:

    very cool, ill give it a shot

  • flisterz said:

    Awesome. Going to try this soon! Too cool to be ignored :D

  • Chris Robinson said:

    again worked awesome!

    one last question i swear ;) how about adding a drop down?

  • Spencer said:

    @Crhis,

    Now that is a little more advanced. Since our data is set up in an array, it is a pretty simple expansion.

    You can check out this tutorial from The Undersigned to see how they used a similar technique for a custom options page in WordPress.

    Basically, you set another value in the array, and then when you are looping through to create the meta boxes, you check to see what type if is based on the value in the array.

    Hope that helps!

  • Max | Design Shard said:

    Great stuff, i may try to upgrade my theme later this week since it is using thumbs just to try this out

    My latest post: Design Vocabulary - Typography Terms - Week 1

  • Felix Ker said:

    Awesome stuff. I gotta do up at my next theme and definitely gonna help things get better with custom panels!

    My latest post: Leaked Pictures: Alyssa Yin Yi (Alyssa Kwan)/ Jane Lo Li (Malaysia Lim Kok Wing University

  • JamieO said:

    While it is still in beta unfortunately, Flutter is a plugin which offers the ability to do this to the write post or any other window. If you are doing this frequently, might be a plugin to look into.

    I’m planning to try it for a recipe blog / site once 2.7 drops.

    My latest post: A taste of things to come with 2.7

  • ChaosKaizer said:

    good tuts, thanks for sharing

    shorten some part of your code

    ID, "image_value", true) ) != "") :
    ?>
    <img src="" alt="" />


    fixed the get_post_meta third parameters, you wont have to write $single = true. I’m sure that was a mistake.

    My latest post: Links for 2008-10-15 [ma.gnolia]

  • Tutorial: Creating Custom Write Panels in WordPress | Wordpress Blog NL said:

    [...] Tutorial: Creating Custom Write Panels in WordPress.: A fantastic, detailed and quite useful tutorial on creating custom write panels for the WordPress Write Post page. I had written something similar for the WordPress Jobs site and it turned out to be a fantastic tool to quickly get to and add/modify Custom Fields in posts. Custom write panels are most useful for customized installations of WordPress and could be used to add many different types of information into a post both easily and quickly. The image below shows a couple of examples of custom panels and I am sure there are hundreds more. [...]

  • ?????WordPress??????? | ???? said:

    [...] ?????: Tutorial: Creating Custom Write Panels in WordPress [...]

  • Dan Harper said:

    Thanks!! I always assumed this could only be done by editing the main WP files (which I obviously, don’t want to do).

    A lot of my themes have loads of Custom Fields, so this will definitely help! :)

  • leg med nye medier. Eller noget. said:

    [...] Function Web Design & Development [ Blog ] » Tutorial: Creating Custom Write Panels in WordPres… (tags: wordpress webdev plugin) [...]

  • WordPress Linktips 20|10|08 said:

    [...] der ‘Neuen Beitrag schreiben’-Seite – wie es gemacht wird erklärt auf englisch Function… Bei BlueAnvil wird schön erklärt wie man ein accessible yet sexy searchbox mit CSS und [...]

  • Ryan said:

    Hi Spencer

    What I meant about being able to post from the front end was like the following demo. http://dailywp.com/classipressdemo/

    They have the add form on what seems to be the front-end. They also seem to be using a custom write panel.

    What do you think, is this easy to do?

    Ryan

  • Simon said:

    Hi Spencer,

    thanks for this great tutorial! It helps me a lot and I implemented it in one of my themes right away.

    Just have one question:

    When saving the postdata shouldn’t we ask as well if the data is not just the default ($meta_box['std'])? For people who set the default the implementation does not work right because the custom value is not empty any more after saving.

    Couldn’t we delete the post meta in the function save_postdata when:
    elseif($data == “” || $data == $meta_box['std'] )

    Thanks again for this awesome post.

    My latest post: Display Future Posts in Your WordPress Theme

  • 7?WordPress???????? | ???? said:

    [...] ???Google Syntax Highlighter for WordPress? ???????/coder ?????????????????????Javascript?????????????????????????WordPress??????????wefunction.com ??????????????????????????? Plain Text ?????????????????????? [...]

  • links for 2008-10-21 said:

    [...] Function Web Design & Development [ Blog ] » Tutorial: Creating Custom Write Panels in WordPres… (tags: wordpress tutorial php) This entry was posted in links. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL. « links for 2008-10-20 [...]

  • Spencer said:

    @Simon,

    Well, if we delete the custom field when the data is equal to our standard value, then the standard value won’t show up, leaving our field empty, when it should have our standard value.

    @Ryan,

    That looks more like a custom form they’ve built. The information is most likely either sent to them in an email, or use some custom PHP and MySQL to post the information into their WP database, tricking it to think that it is an actual post made from the admin panel. That’s what I would do anyway. :P

  • Weblog Tools Collection: Tutorial: Creating Custom Write Panels in WordPress | KaosKoxp Oyun Portali said:

    [...] Collection: Tutorial: Creating Custom Write Panels in WordPress Eki.21, 2008 in Wordpress news Tutorial: Creating Custom Write Panels in WordPress.: A fantastic, detailed and quite useful tutorial on creating custom write panels for the WordPress [...]

  • Simon said:

    @Spencer:

    Sure, you’re right. I was just thinking of a standard value like ‘Enter Image URL here’ without any output in the frontend. Thanks anyway.

    My latest post: Display Future Posts in Your WordPress Theme

  • Spencer said:

    Oh I see what you mean. Yeah you could always add another value to the array, and with a few PHP checks, check if the field has no value yet, and display a description/example inside the actual field. :) I just use the description under the actual input though.

  • élet és könyvtár » Archívum » Ajánlott olvasmány 2008.10.21. said:

    [...] 2 - Function Web Design & Development [ Blog ] » Tutorial: Creating Custom Write Panels in WordPres… [...]

  • How To: Creating Custom Write Panels | WordPress Hacks said:

    [...] to create custom write panels for the Write panel in WordPress?  Look no further than this great tutorial over at We Function. Everyone knows that WordPress is one of the most, if not the most, popular blogging systems on the [...]

  • Bingu said:

    Great tut!
    but, how can I add some custom fields in Press This page?

  • Useful Links (21/10/2008) | Apramana said:

    [...] Creating Custom Write Panels in WordPress [...]

  • WP Log said:

    Tutorial: Creating Custom Write Panels in WordPress…

    A useful tutorial on creating custom write panels for the WordPress Write Post page, and have a example of how useful Custom Fields can be in developing a full CMS with WordPress.
    ……

  • Michael Martin said:

    Great tutorial! I didn’t know you could add new panels for your custom fields. Will try it out, thanks! :D

  • Chris Robinson said:

    @ Spencer

    I’ve been trying to wrap my brain around setting up a dropdown, I’ve got the array setup and working but the loop is whats throwing me.

    Would the modification be done in the foreach(…) section to check and see if its a input or dropdown?

    Then I would add an elseif(…) underneath the first if(…) to add the dropdown to the write panel, right?

    I’m a PHP novice at best, I’ve thrown my code up on pastie:

    http://pastie.org/297278

  • Spencer said:

    @Chris,

    You need to add a new value in your array to define what type of input it will be. Just like you have:

    
    "name" => "area",
    "std" => "Unknown",
    

    You can do something like this:

    
    "name" => "area",
    "std" => "Unknown",
    "type" => "select",
    

    Then in the loop:

    
    foreach($new_meta_boxes as $meta_box) {
    ........
    if($meta_box['type'] == "select") {
       // Build the select box
    }
    .......
    

    Is that what you were having trouble with?

  • Chris Robinson said:

    yep that’s exactly what I needed, but in the example link you posted earlier he’s building the dropdown a little bit differently, I tried to implement his method but I came up with a Parse error.

    code: http://pastie.org/297617

    dropdown is line 34 - 38

    thanks for all your help man, it’s really appreciated :)

  • Links for 21st October 2008 | Velcro City Tourist Board said:

    [...] Tutorial: Creating Custom Write Panels in WordPress [...]

  • Spencer said:

    @Chris,

    
    echo'<?php foreach ($value['options'] as $option) { ?>';
    

    That would be causing your parse error. Try this:

    
    if($meta_box['type'] == "select") {
    
    echo'<select name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" >';
    foreach ($value['options'] as $option) {
    	echo'<option';
    
    	if ( get_settings( $value['id'] ) == $option) {
    		echo ' selected="selected"';
    	} elseif ($option == $value['std']) {
    		echo ' selected="selected"';
    	}
    
    	echo '>'.$option.'</option>';
    }
    echo'</select>';
    
    }
    
  • Robert Augustin said:

    A great post. Anything to make the client happy! I did notice quite a few clients having difficulties understanding this:

    Upload an image as usual, but don’t insert it in the post, instead get the image ID; if it doesn’t show in the upload box (this happens), then save the post, open up the Media Library, hover over the image and get the ID from the status bar, then go back to the post and insert that ID as a value for the key ‘postimage’.

    This is so much simpler :)
    Thanks a lot!

    My latest post: Magenta Lessons, Part 4: The Wonderful World of Public Relations

  • links for 2008-10-21 | Bojko.dk said:

    [...] Tutorial: Creating Custom Write Panels in WordPres… [...]

  • 21 Most Wanted And Essential Resources Specially If You Are Developer - Opensource, Free and Useful Online Resources for Designers and Developers said:

    [...] Tutorial: Creating Custom Write Panels in WordPress [...]

  • Garritt Hampton said:

    Wow, thanks for the great tip. It is nice to see expert level Wordpress tips once in a while. I will definitely be adding a link to this page on my own blog, and I can’t wait to try using Custom Write Panels in my own blogs. Keep up the good work.

  • Freeware Collection said:

    Thanks for this great tutorial. I’ve bookmarked it :).

    My latest post: Sudokool 2.0

  • ‘Custom Field Template’ Rocks! | mkjones - Michael Kimb Jones said:

    [...] it didn’t work as planned. After many hours toil I was minutes away from using code from this tutorial (adding custom fields to the post screen using theme functions). Thankfully I landed on Custom [...]

  • BlogBuzz October 25, 2008 | Webmaster-Source said:

    [...] Tutorial: Creating Custom Write Panels in WordPress [...]

  • Create Custom Write Panels in WordPress | webdemar.com said:

    [...] from Function Web Design & Development wrote a very good tutorial about how to add custom write panels in WordPress. Learn how to output extra meta boxes in your write posts panel to add custom meta data to your [...]

  • Forexprogramma said:

    ????? ?????? ? ??????????, ??? ????????, ?? ????????.

  • Adrian | Rubiqube said:

    Spencer, I love you man! :) This is one of the best WP tutorials I’ve seen in quite a while. Thanks for sharing! Will definitely come in handy on my current project. I was planning on using Custom Fields, but they seem so obsolete now. ;)

  • Khairil said:

    Wow. this is brilliant.

    What about adding another group of meta boxes?

    Say, I have a group of photo meta boxes: photo1, photo2, photo3. Then I’d like to have a group of quotes meta boxes: quote1, quote2, quote3.

    How do I go about doing that?

  • Spencer said:

    @Khairil

    You’ll probably want to loop through the meta boxes in the create_meta_box() function. Right now, we are just creating one meta box with the content we made in new_meta_boxes() with WordPress’s add_meta_box() function.

    What you are talking about would require the use of multiple add_meta_box()’s

    Hope that helps out.

  • Tutorial: Creating Custom Write Panels in WordPress | Free Blogs said:

    [...] Tutorial: Creating Custom Write Panels in WordPress.: A fantastic, detailed and quite useful tutorial on creating custom write panels for the WordPress Write Post page. I had written something similar for the WordPress Jobs site and it turned out to be a fantastic tool to quickly get to and add/modify Custom Fields in posts. Custom write panels are most useful for customized installations of WordPress and could be used to add many different types of information into a post both easily and quickly. The image below shows a couple of examples of custom panels and I am sure there are hundreds more. [...]

  • Khairil said:

    At a second look. Yup, adding a meta box with a group of custom fields not “a group of meta boxes”.

  • Creating Custom Content Type with Flutter Plugin — WPCandy — WordPress Themes, Plugins, Tips, and Tricks said:

    [...] has been a lot of buzz regarding using WordPress as a CMS lately, with many clever solutions that come up. Today, we will be a bit lazy try to use a plugin that is made precisely for [...]

  • Craig Farrall said:

    Wow, this is excellent I have been looking for this type of thing for a while now, and you have hit the nail on the head. Thanks alot.

    My latest post: WordPress Coolest Blog Competition

  • Chris Robinson said:

    @Spencer

    The dropdown shows up but the options are empty, I also added an elseif statement to the input but the dropdown gets added along with a duplicate input box. Any thoughts?

    code here: http://pastie.org/301528

  • Spencer said:

    @Chris,

    Your options need to be in an array themselves.

    
    "options" => "USA","Europe","Asia","Australia",
    

    Try changing that to:

    
    "options" => array("USA","Europe","Asia","Australia"),
    
  • Din nou despre WP ?i câmpurile personalizate | CNET.ro said:

    [...] materiale recente trateaz? tema câmpurilor personalizate din WordPress. Voi începe cu Tutorial: Creating Custom Write Panels in WordPress. WeFunction explic? în acest articol - nededicat încep?torilor, solicitând cuno?tin?e bune [...]

  • Chris Robinson said:

    Thanks, I made the change but I’m still getting a blank dropdown?

    http://pastie.org/301759

  • Spencer said:

    @Chris,

    Try this for your function Chris. Should work fine. :)

    http://pastie.org/301800

  • Custom Write Panels in WordPress | Gilbert Pellegrom said:

    [...] every post then this might be a tutorial for you. Function have come up with a great tutorial for creating your own custom write panels in wordpress. Well worth a look if you use custom fields a lot in your wordpress [...]

  • Kyle said:

    Wow! What a wonderful tutorial. I’m already dreaming up ways I can use this. Thanks so much.

    I have one quick question though: I would like some meta boxes to only be available when editing the ‘About’ page. Do you know of any way to only display a custom meta box when you are editing a page that has a specific title (best option) or uses a specific template (suitable option)?

    Thanks in advance.

  • Spencer said:

    @Kyle

    You could try something like this:

    
    foreach($new_meta_boxes as $meta_box) {
    	if( $post->ID == 333 ) {
    	   	// Normal Stuff
    	} else {
    		echo'No Options for this Page';
    	}
    }
    

    You will of course need to edit the Page ID (My example shows it as 333).

    You will also need to change

    
    add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );
    

    to

    
    add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'page', 'normal', 'high' );
    

    That just tells the function to show up on the “Page” page instead of the “Post” page.

  • Chris Robinson said:

    @ Spencer

    the dropdown is working perfect but the input textfields have disappeared?

    code: http://pastie.org/302761

    thanks again for all your help

  • Spencer said:

    @Chris,

    Sorry about that. In your array, instead of using “text” as the type, you’re using “input”.

    You’ll just want to change

    
    if( $meta_box['type'] == "text" ) { 
    

    to

    
    if( $meta_box['type'] == "input" ) { 
    
  • Kyle said:

    @Spencer

    That worked brilliantly! I didn’t even consider the possibility that WP still applies an ID to a page even if it’s being edited instead of viewed. Thanks for your help.

    Now I’m going to try and add multiple fields like @Khairil was referring to. Which, thanks to your helpful reply to his question, seems entirely reasonable.

    I think the most incredible part of this tutorial is how quickly and helpfully you have been answering everyone’s questions. Thanks for the time you’ve put in to helping us, it’s greatly appreciated.

  • Kyle said:

    Hmm… I think I’m close, but I’m getting this error:

    Warning: Invalid argument supplied for foreach() in /home/.calloway/ksuchallenge/ksuchallenge.com/fresh/wp-content/themes/ksuchallenge/functions.php on line 237

    So the if statement is working fine, but something is off with the foreach loop that goes through a second array I added. I’ve put my heavily-commented code on Pastie in hopes you could help out:

    http://pastie.org/302941

    Thanks once again!

  • Spencer said:

    @Kyle

    You are getting that error because it believes that array does not exist. Even though it clearly does, you haven’t properly defined it in your function, so it has no access to it.

    Try changing

    
    global $post, $new_meta_boxes;
    

    to

    
    global $post, $new_meta_boxes, $new_meta_boxes_misc;
    

    That should fix you right up. :)

  • Kyle said:

    @Spencer

    Just added it and it works perfectly! I feel kinda silly for missing something that simple.

    Thank you so much for all your help, this is going to help my clients use their site a lot.

  • WordPress’te Özel Yaz?m Paneli Yaratmak · Yakup Gövler'in Not Defteri said:

    [...] ba?lant?lar?n? inceleyebilirsiniz. Kodlar?n tamam?n? buradan indirebilirsiniz. Kaynakça: wefunction.com, WordPress [...]

  • Spencer said:

    @Kyle

    Glad everything is working now :)

  • Chris Robinson said:

    @ Spencer

    Awesome! Everything is working perfect. Thanks again for all the help!! :)

  • Chris Robinson said:

    @ Spencer

    In regards to what Khairil was asking would it be as simple as adding a foreach statement to loop through multiple add_meta_box()’s?

  • Chris Robinson said:

    @ Spencer

    Got the multiple add_meta_box()’s working, but I dunno if its the cleanest way to do it? What do you think?

    code: http://pastie.org/303398

  • Spencer said:

    @Chris

    Glad it works. I’m working on a cleaner way to set up multiple meta boxes. It’s throwing me for a loop (no pun intended), but maybe I’ll be able to figure something out. :)

  • Kyle said:

    @Spencer

    I spoke too soon. It’s building and presenting everything perfectly, but it won’t save the data contained in the second array when the page/post is saved.

    http://pastie.org/303772

  • Kyle said:

    @Spencer

    I figured out another (less elegant) method of doing it, and it works great. Basically, I combined my previous two arrays and added an extra “check” parameter to each field array to check whether it should appear on page ID 2. It feels a bit like a hack, but it works.

    http://pastie.org/303792

    Don’t bother with my previous comment unless you’re bored/interested and thanks again… again.

  • WordPress Post Thumbnails | Webmaster-Source said:

    [...] If you want to make it even simpler, if you have a multi-author blog with some less than knowledgeable authors, for example, you can add an extra “Thumbnail” box to the Write page, which would accept an image URL and store it in a custom field behind the scenes. (If you really want to get fancy, you could probably hook right into the Uploader.) Just follow this tutorial: Creating Custom Write Panels in WordPress. [...]

  • 212 said:

    hello,
    it’s à very good tutorial,
    I have to create 3 Fields that i can insert and update them with Ajax, before i have create new table with 5 field (Id, Id_post, price…)
    how can i do to use Ajax to insert and update this table ?

    thank you

    sorry i don’t speak english very well.

    My latest post: Barack Slideshow : le slideshow élégant

  • 21 Most Useful Free Resources For Designers And Web Developers | SulVision said:

    [...] Tutorial: Creating Custom Write Panels in WordPress [...]

  • Craig Farrall’s Blog » Blog Archive » October Roundup said:

    [...] Creating custom write panels in Wordpress [...]

  • Some Essential Reading from the Design Notebook said:

    [...] “Tutorial - Creating Custom Write Panels in WordPress” on Wefunction.com [...]

  • Abeon Tech said:

    Wow. This is a great tutorial, thanks!

    Loads of info and very detailed.

    Blog Bookmarked :)
    My latest post: Google. A Power Users Guide

  • Web Buckets said:

    Hi buddy,

    nice tutorials… but I’m having problem with mine… error parsing… any solutions? for that…

    My latest post: Dreamweaver CS3: Image Maps

  • JackAttack said:

    Hi,

    Thanks for the excellent tutorial… I wish more people would write about advanced topics such as this!

    I have set up several custom fields, all work fine except the “textarea” one, which strips out html when published… is there any way to get around this? The field will be used for inserting flash video embed code.

    Cheers

    Jack

  • Spencer said:

    @Web Buckets

    Need a little more information if you want me to be able to help you. Do you have a URL to the error? What is the error? Can you show me your functions.php in Pastie

    @Jack

    I’ll have to play around with it later today, but I’m pretty sure I’ll end up using n2lbr, so if you want to see if you can get it to work, go for it. :)

  • Rachel said:

    Excellent Tutorial! I am going to love utilizing this in my blogs.

    Thanks for the helpful tutorial.

    Rachel
    allwebdesignresources.com

    My latest post: Robots.Txt Generators - List of Robots.Txt File Creators

  • sympozium » Blog Archive » Creating Custom Write Panels in WordPress said:

    [...] nice tutorial for creating custom panels in order to have a more friendly theme for your low level clients Share this [...]

  • October’s Tutorial Roundup | Tutorial9 - Tutorial Bliss. said:

    [...] Creating Custom Write Panels in WordPress [...]

  • Mike said:

    It works fantastically, but I was just wondering how would you set it up to accept radio buttons?

    I’ve been trying desperately but to no avail.

  • Chris said:

    Very cool, I wonder though, can you have it so that a particular thumbnail will be posted with every post that is under a given category? So when a user wants to post to a category it’ll give them a default thumbnail unless they specify the use of a different image?

  • Spencer said:

    @Mike,

    I’ll have a mess with it, and get back to you.

    @Chris,

    You could check to see if the field is blank (nothing was specified), and if so, check it by using in_category and show a certain image if it is.

  • Mike said:

    @Spencer,

    Thanks a lot man… but, I think I’ve done it… I’m not sure since I was semi-hacking the code. It seems to work and it’s replicable. So I guess it does work.

    Anyways I’ve implemented it for a menu type interface, here’s the code: http://pastie.org/312006

    I’d still like your ideas and how you’d do it.

    And thanks again for this awesome tutorial!

  • Mike said:

    Gah! The previous pastie is just slightly incorrect… haha, shows me for trying to make it look clearer.

    Anyways here’s a fixed version: http://pastie.org/312013

  • Vardis said:

    WOrks great! Thanks a million. Keep it up.

  • gearhed.com » Blog Archive » October’s Tutorial Roundup said:

    [...] Creating Custom Write Panels in WordPress [...]

  • 10 Steps to a Client Friendly Wordpress CMS | StylizedWeb.com said:

    [...] You can do some manual hard coding, like this tutorial [...]

  • Rajeev Edmonds said:

    Great tut, very useful in creating customized dashboard with desired add-ons.

    My latest post: How To Get Backlinks To Your Blog

  • Creating Custom Write Panels in WordPress- This ‘N That said:

    [...] Creating Custom Write Panels in WordPress - With this, you can take your WordPress to the next level and manage lots of custom content for each post. (this was used to use WordPress as a contact manager) November 17th, 2008 | Posted in Reading « Alternative Website Marketing [...]

  • Geek Week - This week jQuery tutorials, CSS3, & WordPress - PHP, XHTML, Web Design, Flash | JasonCypret.com said:

    [...] Creating Custom Write Panels in WordPress [...]

  • Seppl said:

    Nice Tutorial, but why not just use the “More-Fields-Plugin”?
    http://wordpress.org/extend/plugins/more-fields/

  • Most Wanted WordPress Hacks: 11 New Requests (2) | virology.tv said:

    [...] This detailed tutorial on creating custom write panels for the WordPress Write Post page using “add_meta_box()“ [...]

  • Jordan said:

    Nice tutorial. I have been using custom write panels alot recently and was wondering if there was possibly a way to create a custom write panel for a particular page template? This would be amazing!

  • Spencer said:

    @Jordan,

    Not quite sure what you mean page template. Like only show them on a certain page?

    You could try something like I mentioned a few comments up

  • Chris said:

    @ Spencer

    I’ve setup multiple arrays and they’re showing up but when I got to save it doesn’t save the data entered into the fields for the extra two arrays, could you take a look real quick. I’m thinking it has something to do with the save_postdata loop?

    http://pastie.org/324053

  • Jordan said:

    The method you outlined a few comments up is great and i will be using that asap. Thanks.

    Just to clarify what i was trying to say in my previous comment. I copied this from the codex to explain better than me:

    “Individual Pages can be set to use a specific custom Page Template (a PHP template file, e.g., snarfer.php) you create within your Theme. This new Page Template will then override the default page.php Page Template included with your Theme.”

    Thanks again

  • Spencer said:

    @Chris,

    Yeah you are right, it is the save_postdata loop. There is a foreach loop inside that function that loops through the array. So, as messy as it may be, you’ll really need to do three separate loops. :(

    @Jordan,

    Glad that is working. If you’ve setup a page to use a custom page template, then just use the ID of that page in the code I linked you to, and it will only show up on the page you associated the custom template with.

  • Chris said:

    @ Spencer

    I’ve setup the three seperate save loops but still only the first is saving the data, any ideas?

    http://pastie.org/324840

  • Chris said:

    nevermind got it working :)

  • Seb said:

    Hi,

    Very good tutorial, very helpfull, thanx a lot !

    I have a question : as these are custom fields, their values also appear in the Advanced Options > Custom Fields panel. So there are duplicates in the edit page. Or maybe I did something wrong ? I was wondering if there was a way for the Custom Fields panel not to show these particular values ?

  • Jordan said:

    @Seb

    If you make the key part of your custom
    field begin with an underscore, it won’t
    show up in the custom fields panel.

    _customfield

  • Seb said:

    Thank you very much ! I’ve learned very interesting things today thank to you !

  • Jordan said:

    I used the following code that you provided to kyle to specify a specific page i wanted the custom write panel to appear on:

      foreach($new_meta_boxes as $meta_box) {
        if( $post-&gt;ID == 333 ) {
               // Normal Stuff
            } else {
               echo'No Options for this Page';
           }
       }
    

    I also want to make the add_meta_box dependant on this if statement also but when i try it, the box disappears on all pages.

    My latest post: Windsor, Victoria St, SL4

  • Spencer said:

    @Jordan,

    On the second line of that code, you need to change that 333 to the ID of the page you want the options to show on.

  • WordPress als kundenfreundliches CMS - Beitrag - Schweizer WordPress Magazin said:

    [...] Anleitung zu benutzerdefinierten Feldern (engl.) [...]

  • Tim said:

    Absolutely perfect. Worked like a charm…

  • D said:

    Would it be possible to create multiple boxes? i.e. if I wanted thumbnail options to be under a box called “Post Thumbnail” and contact e-mail information under a “Contact Information” box?

    I saw up there where you would have to loop through the create box, but how would you do that?

  • Function Web Design & Development [ Blog ] » Tutorial: Creating Custom Write Panels in WordPress | Enjoy News, Feeds & Share All Your Favorite Media Online With The Rest Of the World… Video, TV, Shows, Music, Audio, Pictures, Images, Games, News, said:

    [...] View This Article  Email This To A Friend     [...]

  • D said:

    Also, this doesn’t show up when I am editing a ‘page’ rather than a ‘post’ any reason for this?

  • Spencer said:

    @D,

    Regarding your first question, you’ll need to create another variable which holds the different box, then create another loop that loops through the array.

    For the second part, you change:

    
    add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'post', 'normal', 'high' );  
    

    to:

    
    add_meta_box( 'new-meta-boxes', 'Brazen Post Settings', 'new_meta_boxes', 'page', 'normal', 'high' );  
    

    Or you can just add the second one right below it to add it to both pages and posts.

  • Function Web Design & Development [ Blog ] » How-To: Taking WordPress One Step Further said:

    [...] great plugin system, and easy to use administration system, WordPress takes the cake. Using a Custom Write Panel, Custom Options, and manipulating the theme files, the possibilities are almost endless. In This [...]

  • Most Wanted WordPress Hacks: 11 New Requests (2) | Link Archive said:

    [...] This detailed tutorial on creating custom write panels for the WordPress Write Post page using “add_meta_box()“ [...]

  • Custom Write Panel- Schreibpanel aufmotzen said:

    [...] Die Idee dazu stammt nicht von mir. Ich erkläre hier dieses “Plugin”. Der Dank geht an Function . [...]

  • Bernat said:

    Hey Spencer, I’ve read all the comments and had been of great help.

    But I’ve reached a dead end for me. I’m one step back to the solution and sure you can help me.

    I’m trying to condition the the panels to a certain category by the technique you where talking about some lines above, but changit post_ID to cat_ID

    
      foreach($new_meta_boxes as $meta_box) {
       if( $post-&gt;cat_ID == 44 ) {
               // Normal Stuff
            } else {
               echo'No Options for this Page';
           }
       }
    

    I think its the best hint I know in order to do it.
    Thanks again.

    PD: This updating comment thing is really cool, can you tell me the plugin?
    My latest post: The Ultimate Web Design Showcase

  • Spencer said:

    @Bernat

    try $post->post_category

  • Bernat said:

    :S I’m sorry, but the conditional it’s not working. Here’s the whole code:
    http://pastie.org/335703

    My latest post: The Ultimate Web Design Showcase

  • Fabio said:

    Since i already have a running blog i didnt really want to change my old customfield to somecustomfield_VALUE

    Took me a time, changed stuffs here and there but what make my hair fall out (like 3 hours of reading and rereading the code) was that i had to take that boolean statement out

    if ( !wp_verify_nonce( $_POST[$meta_box['name'].’_noncename’], plugin_basename(__FILE__) )) {
    return $post_id;
    }

    Anyway i just didnt really got what those statement actually do, can u explain it better to me?

    Btw u did a GREAT job here, really congratz m8

  • D said:

    @Spencer,

    Thanks for getting back with me Spencer. I am still having a few issues adding another meta box. I create a new $test_meta_boxes variable at the top which includes items in the array, then I just added a new foreach loop *within* the same function new_meta_boxes() - do I need to create a new function? Also, I added on the variable $test_meta_boxes on the other functions.

    How can I get this working?

  • joyoge designers' bookmark said:

    very useful tutorial, thank you so much..

    My latest post: Consistency and Memorability

  • Philips said:

    if I wanted thumbnail options to be under a box called “Post Thumbnail” and contact e-mail information under a “Contact Information” box?

  • Most Wanted WordPress Hacks: 11 New Requests (2) | Lifeonthecouch.com said:

    [...] This detailed tutorial on creating custom write panels for the WordPress Write Post page using “add_meta_box()“ [...]

  • Jon said:

    Could you use this custom write panel to modify the blogroll by adding a field to enter banner links instead of text links? i.e. a field to upload an image to be used in place of the text link when entering a link from the dashboard?

  • A Collection of 15 Useful WordPress Tutorials for 2008 » Papertree Design said:

    [...] Creating Custom Write Panels in WordPress - wefunction.com [...]

  • 11????WordPress???? - ??? said:

    [...] ????????????????????“add_meta_box()“??? [...]

  • 9???WordPress?? | sqboa Blog said:

    [...] ????????????????????????????????????????? ????????WordPress?????????????????????????? ?????????????“add_meta_box()“??? ????????????????????“add_meta_box()“??? [...]

  • Corey Freeman said:

    Awesome tutorial! It totally came in handy for my new project.

  • 11?????? WordPress ?????? at ???????? said:

    [...] ??????????????????????????“?????????”????????????????????? WordPress ??? “add_meta_box()” ??????????????????????????????????? ??????? “add_meta_box()” ???????????????????????? [...]

  • October’s Tutorial Roundup | Castup said:

    [...] Creating Custom Write Panels in WordPress [...]

  • 10 Steps to a Client Friendly Wordpress CMS | Castup said:

    [...] You can do some manual hard coding, like this tutorial [...]

  • A Plugin Rather Than Sleep said:

    [...] doing it, but I really wanted something specific and light-weight.  I followed along with this  custom form tutorial and ended up with a simple little thing. The Hover Lyric entry [...]

  • Stefan said:

    thanks for this excellent post … this really helps a lot in my current project

Your Name: (Required)

Your Email Address: (Required but will be hidden)

Your Website:

Your Comment: (Required)

Note: Use [sourcecode language='your-lang'][/sourcecode] around your code please.


Our Motto

We Pride ourselves on giving you Great design & Functionality, providing a website that will impress on first looks, and continue to impress as you explore it.

We make it as easy as possible for you to look after once we've finished. So if you're after a website or blog design to freshen up you're site we're more than happy to help.