Adding Metaboxes

The metaboxes can be added to a custom post type, or a user profile in the Admin view.

The code below can be placed in a custom plugin or a functions.php file in the active theme. It creates 2 separate boxes for the custom post type called businesses, gives the boxes each a title, and specifies what subroutine code to execute to create the content of each box.

//Metaboxes
// Adding metaboxes
function businesses_metaboxes( ) {
   global $wp_meta_boxes;
   add_meta_box('postbusinessname', __('Business Name'), 'businesses_metaboxes_name', 'businesses', 'normal', 'high');
   add_meta_box('postbusinessdesc', __('Business Description'), 'businesses_metaboxes_desc', 'businesses', 'normal', 'high');
}

add_action( 'add_meta_boxes_businesses', 'businesses_metaboxes' );

This next section creates html inputs for the name and description and fills the values from the post meta if the values exist already.

function businesses_metaboxes_name()
{
    global $post;
    $custom = get_post_custom($post->ID);
    $business_name = isset($custom["business_name"][0])?$custom["business_name"][0]:'';
?>
    <label>Business Name:</label><input name="business_name" value="<?php echo $business_name; ?>">
<?php
}

function businesses_metaboxes_desc()
{
    global $post;
    $custom = get_post_custom($post->ID);
    $business_description = isset($custom["business_description"][0])?$custom["business_description"][0]:'';
?>
    <label>Business Description:</label><input name="business_description" value="<?php echo $business_description; ?>">
<?php
}
 

This last code snippet is triggered when the post is being saved. It saves the values of the fields in your custom meta boxes.

function businesses_save_post()
{
    if(empty($_POST)) return; 
    global $post;
    update_post_meta($post->ID, "business_name", $_POST["business_name"]);
    update_post_meta($post->ID, "business_description", $_POST["business_description"]);
}   

add_action( 'save_post_businesses', 'businesses_save_post' );