How to Add Custom Meta Boxes in WordPress Easily

The add_meta_boxes action hook in WordPress lets you easily insert custom meta boxes on post and page editors. These meta boxes provide an area to handle custom fields and extra post data.

Steps to Add Custom Meta Boxes

Follow the code snippet below to attach a custom meta box to a post type like “post” or “page”.

// Register custom meta box
function my_custom_meta_box() {
    add_meta_box(
        'my_custom_meta_box_id',
        'My Custom Meta Box',
        'display_custom_meta_box',
        'post',
        'normal',
        'high'
    );
}
add_action( 'add_meta_boxes', 'my_custom_meta_box' );

// Display box content
function display_custom_meta_box( $post ) {
    $custom_field_value = get_post_meta( $post->ID, '_custom_field_key', true );
    wp_nonce_field( 'my_custom_meta_box_nonce_action', 'my_custom_meta_box_nonce' );
    ?>
    <label for="custom_field">Custom Field:</label>
    <input type="text" id="custom_field" name="custom_field" value="<?php echo esc_attr( $custom_field_value ); ?>" style="width: 100%;">
    <?php
}

// Save meta box data
function save_custom_meta_box_data( $post_id ) {
    if ( ! isset( $_POST['my_custom_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['my_custom_meta_box_nonce'], 'my_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['custom_field'] ) ) {
        update_post_meta( $post_id, '_custom_field_key', sanitize_text_field( $_POST['custom_field'] ) );
    }
}
add_action( 'save_post', 'save_custom_meta_box_data' );

This function set adds a text input field within a custom meta box to the post editing interface.

Helpful Tips

  • Always use unique IDs for your meta boxes and nonces to avoid plugin conflicts.
  • Adapt the HTML inside the display_custom_meta_box function to your project requirements.

Now you can manage custom fields directly from the post editor screen. For more details, visit WordPress Developer Resources.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.