Using WordPress ‘add_meta_box()’ PHP function

The add_meta_box() WordPress PHP function is used to add a meta box to one or more screens in the WordPress admin.

Usage

add_meta_box( 'my_meta_box_id', 'My Meta Box Title', 'my_meta_box_callback', 'post', 'normal', 'default', array('key' => 'value') );

Parameters

  • $id (string) Required: Meta box ID (used in the ‘id’ attribute for the meta box).
  • $title (string) Required: Title of the meta box.
  • $callback (callable) Required: Function that fills the box with the desired content. The function should echo its output.
  • $screen (string|array|WP_Screen) Optional: The screen or screens on which to show the box (such as a post type, ‘link’, or ‘comment’). Default is the current screen.
  • $context (string) Optional: The context within the screen where the box should display. Global default is ‘advanced’.
  • $priority (string) Optional: The priority within the context where the box should show. Default ‘default’.
  • $callback_args (array) Optional: Data that should be set as the $args property of the box array (which is the second parameter passed to your callback).

More information

See WordPress Developer Resources: add_meta_box()

Examples

Add a simple meta box to the post edit screen

This example demonstrates how to add a simple meta box to the post edit screen.

// Register meta box
function my_simple_meta_box() {
    add_meta_box('simple_meta_box', 'Simple Meta Box', 'simple_meta_box_callback', 'post');
}
add_action('add_meta_boxes', 'my_simple_meta_box');

// Meta box display callback
function simple_meta_box_callback($post) {
    echo 'This is a simple meta box!';
}

Add a custom meta box with an input field to the post edit screen

This example demonstrates how to add a custom meta box with an input field to the post edit screen.

// Register meta box
function my_custom_meta_box() {
    add_meta_box('custom_meta_box', 'Custom Meta Box', 'custom_meta_box_callback', 'post');
}
add_action('add_meta_boxes', 'my_custom_meta_box');

// Meta box display callback
function custom_meta_box_callback($post) {
    // Add a nonce for security and authentication
    wp_nonce_field('custom_meta_box_nonce_action', 'custom_meta_box_nonce');

    // Retrieve an existing value from the database
    $custom_value = get_post_meta($post->ID, 'custom_value_key', true);

    // Display the form, using the current value
    echo '<label for="custom_value">Custom Value:</label>';
    echo '<input type="text" id="custom_value" name="custom_value" value="' . esc_attr($custom_value) . '" size="30" />';
}