0
0
WordpressHow-ToBeginner · 4 min read

How to Create a Metabox in WordPress: Simple Guide

To create a metabox in WordPress, use the add_meta_box function inside the add_meta_boxes action hook to register it. Then, save the metabox data using the save_post hook to store custom information with posts.
📐

Syntax

The add_meta_box function registers a metabox with these main parts:

  • $id: Unique ID for the metabox.
  • $title: The box title shown in the editor.
  • $callback: Function to display the metabox content.
  • $screen: Post type(s) where the box appears.
  • $context: Location on the edit screen (normal, side, advanced).
  • $priority: Order priority (default, high, low).

Use add_action('add_meta_boxes', 'your_function') to hook your metabox registration.

php
add_action('add_meta_boxes', 'custom_metabox_register');

function custom_metabox_register() {
    add_meta_box(
        'custom_metabox_id',       // Unique ID
        'Custom Metabox Title',    // Box title
        'custom_metabox_callback', // Callback function
        'post',                    // Screen (post type)
        'normal',                  // Context
        'default'                  // Priority
    );
}

function custom_metabox_callback($post) {
    // Display metabox content here
}
💻

Example

This example creates a metabox on the post edit screen that lets you enter a subtitle. It saves the subtitle as post meta when you save the post.

php
<?php
// Register metabox
add_action('add_meta_boxes', 'subtitle_metabox_register');
function subtitle_metabox_register() {
    add_meta_box(
        'subtitle_metabox',
        'Post Subtitle',
        'subtitle_metabox_callback',
        'post',
        'normal',
        'default'
    );
}

// Display metabox content
function subtitle_metabox_callback($post) {
    // Add a nonce field for security
    wp_nonce_field('subtitle_metabox_nonce_action', 'subtitle_metabox_nonce');

    // Get existing value
    $subtitle = get_post_meta($post->ID, '_post_subtitle', true);

    echo '<label for="post_subtitle">Subtitle:</label> ';
    echo '<input type="text" id="post_subtitle" name="post_subtitle" value="' . esc_attr($subtitle) . '" size="25" />';
}

// Save metabox data
add_action('save_post', 'subtitle_metabox_save');
function subtitle_metabox_save($post_id) {
    // Check nonce
    if (!isset($_POST['subtitle_metabox_nonce']) || !wp_verify_nonce($_POST['subtitle_metabox_nonce'], 'subtitle_metabox_nonce_action')) {
        return;
    }

    // Check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // Check user permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // Save or delete subtitle
    if (isset($_POST['post_subtitle'])) {
        update_post_meta($post_id, '_post_subtitle', sanitize_text_field($_POST['post_subtitle']));
    } else {
        delete_post_meta($post_id, '_post_subtitle');
    }
}
?>
Output
A new metabox titled 'Post Subtitle' appears on the post edit screen with a text input. When saved, the subtitle is stored as post meta and can be retrieved later.
⚠️

Common Pitfalls

  • Forgetting to add a nonce field and verify it can cause security issues.
  • Not checking for autosave or user permissions may lead to unwanted data changes.
  • Using wrong $screen value in add_meta_box means the box won't show.
  • Not sanitizing input before saving can cause security risks.
php
<?php
// Wrong: No nonce check or permission check
add_action('save_post', function($post_id) {
    if (isset($_POST['post_subtitle'])) {
        update_post_meta($post_id, '_post_subtitle', $_POST['post_subtitle']);
    }
});

// Right: Proper nonce and permission checks
add_action('save_post', function($post_id) {
    if (!isset($_POST['subtitle_metabox_nonce']) || !wp_verify_nonce($_POST['subtitle_metabox_nonce'], 'subtitle_metabox_nonce_action')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (isset($_POST['post_subtitle'])) {
        update_post_meta($post_id, '_post_subtitle', sanitize_text_field($_POST['post_subtitle']));
    }
});
?>
📊

Quick Reference

  • add_meta_box: Registers the metabox.
  • add_action('add_meta_boxes'): Hook to add your metabox.
  • Callback function: Outputs the HTML inside the metabox.
  • save_post: Hook to save metabox data securely.
  • Nonce: Protects against unauthorized saves.

Key Takeaways

Use add_meta_box inside add_meta_boxes hook to create a metabox.
Always add nonce and permission checks when saving metabox data.
Sanitize user input before saving to the database.
Use save_post hook to save metabox data securely.
Test metabox on the correct post type and screen context.