Meta boxes are used in WordPress posts. The Excerpt function, and the tags function, are examples of meta boxes. To create a Meta Box in a plugin, simply use this code:
<?php
/* Define the custom box */
// WP 3.0+
// add_action( 'add_meta_boxes', 'addmymeta_add_custom_box' );
// backwards compatible
add_action( 'admin_init', 'addmymeta_add_custom_box', 1 );
/* Do something with the data entered */
add_action( 'save_post', 'addmymeta_save_postdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function addmymeta_add_custom_box() {
add_meta_box(
'addmymeta_sectionid',
__( 'My Post Section Title', 'addmymeta_textdomain' ),
'addmymeta_inner_custom_box',
'post'
);
add_meta_box(
'addmymeta_sectionid',
__( 'My Post Section Title', 'addmymeta_textdomain' ),
'addmymeta_inner_custom_box',
'page'
);
}
/* Prints the box content */
function addmymeta_inner_custom_box() {
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'addmymeta_noncename' );
// The actual fields for data entry
echo '<label for="addmymeta_new_field">';
_e("Description for this field", 'addmymeta_textdomain' );
echo '</label> ';
echo '<input type="text" id="addmymeta_new_field" name="addmymeta_new_field" value="whatever" size="25" />';
}
/* When the post is saved, saves our custom data */
function addmymeta_save_postdata( $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;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['addmymeta_noncename'], plugin_basename( __FILE__ ) ) )
return;
// Check permissions
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// OK, we're authenticated: we need to find and save the data
$mydata = $_POST['myplugin_new_field'];
// Do something with $mydata
// probably using add_post_meta(), update_post_meta(), or
// a custom table (see Further Reading section below)
return $mydata;
}
?>