Register Single Meta Box (Deprecated)

This method is deprecated since v4.3.6. See this tutorial for a better method of registering meta boxes.

The code below registers a single meta box (if you want to register multiple meta boxes at once, please read this tutorial), put this into functions.php file of your theme or into your plugin:

add_action( 'admin_init', 'rw_register_meta_box' );

function rw_register_meta_box()
{
    // Check if plugin is activated or included in theme
    if ( !class_exists( 'RW_Meta_Box' ) )
        return;

    $prefix = 'rw_';

    $meta_box = array(
        'id'       => 'personal',
        'title'    => 'Personal Information',
        'pages'    => array( 'post', 'page' ),
        'context'  => 'normal',
        'priority' => 'high',

        'fields' => array(
            array(
                'name'  => 'Full name',
                'desc'  => 'Format: First Last',
                'id'    => $prefix . 'fname',
                'type'  => 'text',
                'std'   => 'Anh Tran',
                'class' => 'custom-class',
                'clone' => true,
            ),
        )
    );

    new RW_Meta_Box( $meta_box );
}

Hook

In the code above, we hook into admin_init, which means when the admin area is ready. This makes sure the plugin is loaded and the code won’t be broken.

The benefit of using admin_init is you can get other useful information when admin area is ready such as post ID, information about current screen, etc, which can be used later for some conditions.

Another advantage of this method is it runs only in admin area, which means your website will run fast in the front-end.

Prefix

In the beginning of the code, we defined a prefix:

$prefix = 'rw_';

It will be added before all of our custom field IDs. Using prefix can prevent us from conflict with other scripts that also use custom fields.

Note that this prefix is optional. You can delete it if you want, and remember to remove it from the field IDs in that case.

Meta box attributes

Now let’s talk the main thing – meta box attributes. Each meta box has the following attributes:

  • id: meta box ID. Optional. If it’s absent, it will be generated from title using sanitize_title function.
  • title: meta box title. Required.
  • pages: array of custom post types. Optional. Default: array('post').
  • context: part of the page where the meta box is displayed (normal, advanced or side). Optional. Default: normal.
  • priority: priority within the context where the box is displayed (high or low). Optional. Default: high.

Each meta box has a list of fields, which represent itself an array. Each array contains information about one field. To understand how to define fields, please read this tutorial.

See more tutorials