0
0
Wordpressframework~5 mins

Custom meta boxes in Wordpress

Choose your learning style9 modes available
Introduction

Custom meta boxes let you add extra fields to WordPress posts or pages. This helps you store and show more information easily.

You want to add a special input field for extra details on posts.
You need to collect custom data like ratings or dates from users.
You want to organize extra information in a neat box on the edit screen.
You want to save and display custom settings for each post or page.
Syntax
Wordpress
<?php
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box_id',       // Unique ID
        'Custom Meta Box Title',    // Box title
        'custom_meta_box_callback', // Callback function
        'post',                     // Screen to show on (post, page, custom post type)
        'normal',                   // Context (normal, side, advanced)
        'high'                      // Priority
    );
}
add_action('add_meta_boxes', 'add_custom_meta_box');

function custom_meta_box_callback($post) {
    // Add nonce for security
    wp_nonce_field('custom_meta_box_nonce_action', 'custom_meta_box_nonce');

    // Get existing value if any
    $value = get_post_meta($post->ID, '_custom_meta_key', true);

    // Display input field
    echo '<label for="custom_field">Custom Field:</label>';
    echo '<input type="text" id="custom_field" name="custom_field" value="' . esc_attr($value) . '" size="25" />';
}

function save_custom_meta_box_data($post_id) {
    // Check nonce
    if (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], 'custom_meta_box_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 meta
    if (isset($_POST['custom_field'])) {
        update_post_meta($post_id, '_custom_meta_key', sanitize_text_field($_POST['custom_field']));
    } else {
        delete_post_meta($post_id, '_custom_meta_key');
    }
}
add_action('save_post', 'save_custom_meta_box_data');

The add_meta_box function adds the box to the edit screen.

The callback function outputs the HTML for the box content.

Examples
This example shows how to add the meta box to pages instead of posts.
Wordpress
<?php
// Add meta box to pages instead of posts
function add_custom_meta_box_page() {
    add_meta_box('custom_meta_box_id', 'Page Meta Box', 'custom_meta_box_callback', 'page');
}
add_action('add_meta_boxes', 'add_custom_meta_box_page');
This example changes the input field to a textarea for longer text.
Wordpress
<?php
// Use a textarea instead of input
function custom_meta_box_callback($post) {
    wp_nonce_field('custom_meta_box_nonce_action', 'custom_meta_box_nonce');
    $value = get_post_meta($post->ID, '_custom_meta_key', true);
    echo '<label for="custom_field">Description:</label>';
    echo '<textarea id="custom_field" name="custom_field" rows="4" cols="30">' . esc_textarea($value) . '</textarea>';
}
Sample Program

This code adds a meta box titled "Favorite Color" on the side of the post edit screen. It shows a text input where you can type a color. When you save the post, it stores the color as post meta data.

Wordpress
<?php
// Add a custom meta box to posts
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box_id',
        'Favorite Color',
        'custom_meta_box_callback',
        'post',
        'side',
        'default'
    );
}
add_action('add_meta_boxes', 'add_custom_meta_box');

function custom_meta_box_callback($post) {
    wp_nonce_field('custom_meta_box_nonce_action', 'custom_meta_box_nonce');
    $value = get_post_meta($post->ID, '_favorite_color', true);
    echo '<label for="favorite_color">Favorite Color:</label><br />';
    echo '<input type="text" id="favorite_color" name="favorite_color" value="' . esc_attr($value) . '" size="20" />';
}

function save_custom_meta_box_data($post_id) {
    if (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], 'custom_meta_box_nonce_action')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    if (isset($_POST['favorite_color'])) {
        update_post_meta($post_id, '_favorite_color', sanitize_text_field($_POST['favorite_color']));
    } else {
        delete_post_meta($post_id, '_favorite_color');
    }
}
add_action('save_post', 'save_custom_meta_box_data');
OutputSuccess
Important Notes

Always use wp_nonce_field and check nonce to secure your meta box.

Use sanitize_text_field or similar functions to clean user input before saving.

Remember to check user permissions to avoid unauthorized changes.

Summary

Custom meta boxes add extra fields to WordPress edit screens.

Use add_meta_box to create the box and a callback to show fields.

Save data securely using save_post action with nonce and permission checks.