Function Web Design & Development [ Blog ] ? ...
Use Custom Write options to easily add any unique data to your post
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.
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
view plaincopy to clipboardprint- /*
- 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(
- );
/*Plugin Name: Custom Write PanelPlugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpressDescription: Allows custom fields to be added to the WordPress Post PageVersion: 1.0Author: SpencerAuthor 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 \"Add an Image\" button, upload an image and paste the URL here.")
- );
$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."));
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 ) {
- }
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;
- }
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) {
- }
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'];
- }
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.
view plaincopy to clipboardprint- echo'';
echo'';
Now we can echo
the title of our Custom Input:
- echo'
'.$meta_box['title'].'
';
echo''.$meta_box['title'].'
';
Next our actual input box. This gets the value of $meta_box_value
we worked out earlier.
- echo'
';
echo'
';
Finally, just add our little description we defined in the array
- echo'';
echo'';
(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' );
- }
- }
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:
view plaincopy to clipboardprintcallback
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.
view plaincopy to clipboardprint- function save_postdata( $post_id ) {
- global $post, $new_meta_boxes;
- foreach($new_meta_boxes as $meta_box) {
- }
- }
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;
- }
// Verifyif ( !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.
view plaincopy to clipboardprint- $data = $_POST[$meta_box['name'].'_value'];
$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);
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.
view plaincopy to clipboardprint- elseif($data != get_post_meta($post_id, $meta_box['name'].'_value', true))
- update_post_meta($post_id, $meta_box['name'].'_value', $data);
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.
view plaincopy to clipboardprint- elseif($data == "")
- delete_post_meta($post_id, $meta_box['name'].'_value', get_post_meta($post_id, $meta_box['name'].'_value', true));
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');
add_action('admin_menu', 'create_meta_box');add_action('save_post', 'save_postdata');
Our Final Code
view plaincopy to clipboardprint- /*
- 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 \"Add an Image\" button, upload an image and paste the URL here.")
- );
/*Plugin Name: Custom Write PanelPlugin URI: http://wefunction.com/2008/10/tutorial-create-custom-write-panels-in-wordpressDescription: Allows custom fields to be added to the WordPress Post PageVersion: 1.0Author: SpencerAuthor URI: http://wefunction.com/* ----------------------------------------------*/$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."));view plaincopy to clipboardprint
- 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'];
- echo'';
- echo'
'.$meta_box['title'].'
'; - echo'
'; - echo'';
- }
- }
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'];echo'';echo'view plaincopy to clipboardprint'.$meta_box['title'].'
';echo'
';echo'';}}
- 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 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' );}}view plaincopy to clipboardprint
- 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));
- }
- }
function save_postdata( $post_id ) {global $post, $new_meta_boxes;foreach($new_meta_boxes as $meta_box) {// Verifyif ( !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));}}view plaincopy to clipboardprint
- add_action('admin_menu', 'create_meta_box');
- add_action('save_post', 'save_postdata');
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.)
view plaincopy to clipboardprint- if(get_post_meta($post->ID, "image_value", $single = true) != "") :
- ?>
ID, "image_value", $single = true) != "") :?>
Now the actual image:
view plaincopy to clipboardprintsrc=" echo get_post_meta($post->ID, "image_value", $single = true); ?>" alt="" />
" alt="" />
And to end our if
statement:
- 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