Create Custom Meta Boxes with add_meta_boxes in WordPress

Using the add_meta_boxes hook in WordPress, you can add custom sections—called meta boxes—to the post or page edit screens. These boxes let you manage extra information or fields tied to a post.

Adding a Custom Meta Box

Here’s a basic code snippet to create and display a custom meta box for posts:

// Hook to add the 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 meta 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">Enter Value:</label>
    <input type="text" id="custom_field" name="custom_field" value="<?php echo esc_attr( $custom_field_value ); ?>" style="width: 100%;">
    <?php
}

// Save meta 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' );

With this implementation, a custom meta box will appear in the post editor and allow input of a custom field value.

Things to Keep in Mind

  • Unique IDs for your fields and nonces are crucial for plugin/theme compatibility.
  • Customize the HTML in display_custom_meta_box() to fit your design.

This approach is highly flexible for extending the WordPress post editor. Visit official developer docs for more advanced usage.

 

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.