Creating Custom Meta Boxes in WordPress

1 comment
Going further in depths of WordPress today we will learn how to add Custom Meta Boxes to Write Post, Write Page, and Write Link editing pages. WordPress provides the function 'add_meta_box()' for adding meta boxes. This function takes 7 parameters which are as follows:

  • $id: HTML 'id' attribute of the edit screen section
  • $title: Title of the edit screen section, visible to user
  • $callback: Function that prints out the HTML for the edit screen section.
  • $page: The type of Write screen on which to show the edit screen section ('post', 'page', 'link', or 'custom_post_type' where custom_post_type is the custom post type slug)
  • $context: The part of the page where the edit screen section should be shown ('normal', 'advanced', or 'side')
  • $priority: The priority within the context where the boxes should show ('high' or 'low')
  • $callback_args: Arguments to pass into your callback function. The callback will receive the $post object and whatever parameters are passed through this variable.



But you must be careful in using this function because 'add_meta_boxes' action is not available in versions before 3.0. We will start our code by checking the WordPress version. For this also we will create a new plugin. Lets see the code:

<?php
/*
Plugin Name: Add Meta Boxes
Plugin URI: http://webspeaks.in/
Description: Add new Meta Box.
Author: Arvind Bhardwaj
Version: 1.0
Author URI: http://webspeaks.in/
*/
?>
<?php
global $wp_version;
if (version_compare($wp_version,"3.0","<")) /*provides the current WordPress version in standard format*/
{
 add_action('admin_init', 'addMetaBox', 1); /*for versions < 3.0*/
}
else
{
 add_action('add_meta_boxes', 'addMetaBox'); /*for versions >=3.0*/
}

function addMetaBox()
{
 add_meta_box( 'boxId', __( 'My Custom Box', 'myplugin_textdomain' ), 'renderHtml', 'post', 'normal', 'high', array('showname'=>true, 'showage'=>false, 'showaddress'=>true) );
}

function renderHtml($post, $params) /*Callback function for creating html part of the meta box*/
{
 $myParams = $params['args']; /*Receive callback parameters*/

 if($myParams['showname']) /*Generate HTML based on callback parameters*/
 {
?>
 <label for="myname">Enter Your Name</label><br />
 <input type="text" name="myname" id="myname" /><br /><br />
<?php
 }
 
 if($myParams['showage'])
 {
?>
 <label for="myage">Enter Your Age</label><br />
 <input type="text" name="myage" id="myage" /><br /><br />
<?php
 }

 if($myParams['showaddress'])
 {
?>
 <label for="myaddress">Enter Your Address</label><br />
 <input type="text" name="myaddress" id="myaddress" />
<?php
 }
 wp_nonce_field( plugin_basename(__FILE__), 'myNonce' ); /* used for verification*/
}
?>

The code is self explanatory in itself. We have just added a meta box in post page and added HTML in it. Now activate the plugin from plugins page.  It outputs following plugin:

Now you will see the new custom box in the post page. Till now it solves no special purpose as it just shows you few text boxes. You will need to perform some actions on these values. This task will be done on 'save_post' hook of WordPress.

Processing the Input Fields:
<?php
/* Do something with the data entered */
add_action('save_post', 'saveMyData');

function saveMyData( $post_id )
{
 // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything
 if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
  return $post_id;

 if ( !wp_verify_nonce( $_POST['myNonce'], plugin_basename(__FILE__) ))
 {
  return $post_id;
 }

 // Check permissions
 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;
 }

 $myName = $_POST['myname'];
 $myAge = $_POST['myage'];
 
 /*Now you can $myName and $myAge to a custom table or to meta options using add_post_meta()*/
}
?>
We have just called 'saveMyData()' function on 'save_post' hook. In 'saveMyData()' we will process our custom inputs and save them somewhere in the database according to our needs.

Complete code:
<?php
/*
Plugin Name: Add Meta Boxes
Plugin URI: http://webspeaks.in/
Description: Add new Meta Box.
Author: Arvind Bhardwaj
Version: 1.0
Author URI: http://webspeaks.in/
*/
?>
<?php
global $wp_version;
if (version_compare($wp_version,"3.0","<")) /*provides the current WordPress version in standard format*/
{
 add_action('admin_init', 'addMetaBox', 1); /*for versions < 3.0*/
}
else
{
 add_action('add_meta_boxes', 'addMetaBox'); /*for versions >=3.0*/
}

function addMetaBox()
{
 add_meta_box( 'boxId', __( 'My Custom Box', 'myplugin_textdomain' ), 'renderHtml', 'post', 'normal', 'high', array('showname'=>true, 'showage'=>false, 'showaddress'=>true) );
}

function renderHtml($post, $params)
{
 $myParams = $params['args'];

 if($myParams['showname'])
 {
?>
 <label for="myname">Enter Your Name</label><br />
 <input type="text" name="myname" id="myname" /><br /><br />
<?php
 }
 
 if($myParams['showage'])
 {
?>
 <label for="myage">Enter Your Age</label><br />
 <input type="text" name="myage" id="myage" /><br /><br />
<?php
 }

 if($myParams['showaddress'])
 {
?>
 <label for="myaddress">Enter Your Address</label><br />
 <input type="text" name="myaddress" id="myaddress" />
<?php
 }

 // Use nonce for verification
 wp_nonce_field( plugin_basename(__FILE__), 'myNonce' );
}
?>
<?php
/* Do something with the data entered */
add_action('save_post', 'saveMyData');

function saveMyData( $post_id )
{
 // verify if this is an auto save routine. If it is our form has not been submitted, so we dont want to do anything
 if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
  return $post_id;

 if ( !wp_verify_nonce( $_POST['myNonce'], plugin_basenamemyName = $_POST['myname'];
 $myAge = $_POST['myage'];
 
 /*Now you can $myName and $myAge to a custom table or to meta options using add_post_meta()*/
}
?>

NOTE : DO not leave any space between ending and starting tags of PHP (?> and <?php) or before or after ?> and <?php other wise it will give you 'Headers already sent...' error!

1 comments:

This is my first visit to your site. Today I have got a new site. I am really happy to be here. I am stay tuned here for your next blog...

We would love to hear from you...

back to top