Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 68 ยท Custom Post Types, Taxonomies and Fields

Meta Boxes and Saving Data

Build WordPress meta boxes: add_meta_box, rendering fields, nonces, safe save_post checks for autosave and capabilities, sanitizing, and block editor panels.

You can store extra data with post meta, but editors need somewhere to type it. A meta box is a panel on the post editing screen that holds your own form fields. A "Book details" box with an ISBN and a price is a typical example. WordPress draws the box, but it is up to you to print the inputs and, more importantly, to save them safely.

Saving is where bugs and vulnerabilities hide. The save_post hook runs in many situations: autosaves, quick edits, imports and revisions. A careless handler can overwrite data, let the wrong user change a post, or save unchecked input. This lesson shows the full pattern: register the box, render it with a nonce, then check, sanitize and save. It ends with how the block editor treats meta boxes and what its sidebar panels look like.

The real functions only run inside WordPress, so the real code below is read-only. The runnable examples are plain-PHP stand-ins for the nonce, capability and sanitizing steps, which are the parts worth practicing. They are simplified, not core code.

Registering a meta box

Use the add_meta_boxes action. The add_meta_box() function takes an ID, a title, a render callback and the screen (the post type) where it should appear:

PHP
<?php
function acme_add_book_meta_box(): void {
    add_meta_box(
        'acme_book_details',          // unique HTML id
        'Book details',               // title
        'acme_render_book_meta_box',  // callback that prints the fields
        'book',                       // post type (a string or an array)
        'side',                       // context: normal, side or advanced
        'default'                     // priority: high, core, default or low
    );
}
add_action( 'add_meta_boxes', 'acme_add_book_meta_box' );

The context decides where the box sits: normal under the editor, side in the sidebar, advanced below normal. The priority orders boxes inside a context. Editors can drag boxes around and hide them with Screen Options, so never rely on a fixed position. You can also use add_meta_boxes_{post_type} to register only for one type. Hooks are explained in actions and filters.

sequenceDiagram
    participant U as Editor
    participant W as WordPress
    participant P as Your plugin
    U->>W: Open the edit screen
    W->>P: add_meta_boxes
    P-->>W: add_meta_box(...)
    W->>P: Render callback (prints fields and nonce)
    U->>W: Click Update
    W->>P: save_post_book
    P->>P: Check nonce, autosave, capability
    P->>P: Sanitize, then update_post_meta

Rendering adds a nonce to the form; saving checks it, then the user's rights, then cleans the input.

Rendering the fields

The callback receives the current $post. Print a nonce field first, then your inputs, filled with the current values. Always escape what you print:

PHP
<?php
function acme_render_book_meta_box( WP_Post $post ): void {
    wp_nonce_field( 'acme_save_book', 'acme_book_nonce' );

    $isbn  = get_post_meta( $post->ID, '_acme_isbn', true );
    $price = get_post_meta( $post->ID, '_acme_price', true );
    ?>
    <p>
        <label for="acme_isbn">ISBN</label><br>
        <input type="text" id="acme_isbn" name="acme_isbn"
               value="<?php echo esc_attr( $isbn ); ?>">
    </p>
    <p>
        <label for="acme_price">Price</label><br>
        <input type="number" step="0.01" min="0" id="acme_price" name="acme_price"
               value="<?php echo esc_attr( $price ); ?>">
    </p>
    <?php
}

wp_nonce_field( 'acme_save_book', 'acme_book_nonce' ) prints a hidden input named acme_book_nonce that carries a one-time-style token tied to the action name, the user and a time window. When the form comes back, you check the token. A nonce proves the request came from your form on a page the logged-in user loaded, which blocks cross-site request forgery. It is not a permission check, and it does not protect against anything a logged-in user may legitimately do. Forms and nonces goes deeper.

Note the leading underscores in _acme_isbn: these are protected keys, hidden from the Custom Fields box, so editors only use your nicer form.

This stand-in builds the same markup in plain PHP. It uses htmlspecialchars() in place of esc_attr(), and a fake nonce, so you can see what an escaped value looks like when the stored text has a quote in it.

PHP Rendering a meta box with escaping and a nonce field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In the second output the quote and angle brackets became &quot;, &gt; and &lt;, so the stored text stays inside the value attribute and cannot break out of it. Without esc_attr() the first quote would close the attribute and the rest would run as markup. See escaping output.

Saving with save_post

When the post is saved, WordPress fires save_post and save_post_{post_type} with the post ID, the post object and whether it is an update. Use the type-specific hook so your code does not run for pages and posts. The handler must do these checks in this order, and stop (return) at the first failure:

  1. Nonce present and valid. If the field is missing, the request did not come from your form.
  2. Not an autosave. WordPress autosaves in the background and the autosave request does not include your fields, so saving then would erase data. Check defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE.
  3. Not a revision. Revisions trigger save_post too. wp_is_post_revision( $post_id ) catches them.
  4. The user may edit this post. current_user_can( 'edit_post', $post_id ).
  5. Sanitize every value, then save it.
PHP
<?php
function acme_save_book_meta( int $post_id ): void {
    if ( ! isset( $_POST['acme_book_nonce'] ) ) {
        return;
    }
    $nonce = sanitize_text_field( wp_unslash( $_POST['acme_book_nonce'] ) );
    if ( ! wp_verify_nonce( $nonce, 'acme_save_book' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( wp_is_post_revision( $post_id ) ) {
        return;
    }
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    if ( isset( $_POST['acme_isbn'] ) ) {
        $isbn = preg_replace( '/[^0-9Xx-]/', '', wp_unslash( $_POST['acme_isbn'] ) );
        update_post_meta( $post_id, '_acme_isbn', $isbn );
    }

    if ( isset( $_POST['acme_price'] ) ) {
        $price = max( 0, (float) wp_unslash( $_POST['acme_price'] ) );
        update_post_meta( $post_id, '_acme_price', number_format( $price, 2, '.', '' ) );
    }
}
add_action( 'save_post_book', 'acme_save_book_meta' );

Some notes on this code:

  • wp_unslash() comes first. WordPress adds slashes to $_POST for historical reasons. Remove them before you sanitize, and update_post_meta() then handles slashing itself.
  • Use the right sanitizer for each field: sanitize_text_field() for plain text, absint() for IDs, sanitize_email() for emails, wp_kses_post() for limited HTML, esc_url_raw() for URLs you store. Sanitizing and validating input covers these.
  • Validate as well as sanitize. A negative price is clean text but wrong data, so the example clamps it.
  • Update a field only if it is present in $_POST. Unchecked checkboxes are missing from the request, so handle them by deleting the meta or setting it to 0 when the box was in the form.
  • If your handler calls wp_update_post(), remove and re-add your hook around it, or it will call itself forever.

Why every check matters

The nonce and the capability check do different jobs. The nonce says "this request came from the form we printed". The capability check says "this user is allowed to edit this post". A request can pass one and fail the other, for example a contributor submitting your form for someone else's post. Skipping the autosave check is the classic data-loss bug, because the autosave payload lacks your fields.

A full save flow you can run

This stand-in strings the five checks together and runs six requests through them. The nonce is a keyed hash tied to the action, the user and a time tick; capabilities are a plain list.

PHP The save_post flow with nonce, capability and sanitizing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the table of results: the valid request passes and its dirty ISBN is cleaned, the nonce one tick old still works, two ticks old does not, and a nonce made for another user or action is rejected. The final stored price is the clamped 0.00 from the negative case, which ran last. This is also why the nonce tick exists: tokens expire.

Block editor compatibility

The block editor still displays classic meta boxes, but it treats them as second-class. Your boxes appear in a section below the content, and the editor saves them with a separate request after the post itself, so a plugin must not assume the same request carries both. The old save_post pattern still works for this reason, with the nonce check as written above.

For a modern experience, use a sidebar panel instead. You register the field with register_post_meta() and show_in_rest (see custom fields), then build a panel in JavaScript that edits the meta through the editor's data store. A small example, which is real code and read-only here:

JavaScript
import { registerPlugin } from '@wordpress/plugins';
import { PluginDocumentSettingPanel } from '@wordpress/editor';
import { TextControl } from '@wordpress/components';
import { useEntityProp } from '@wordpress/core-data';
import { useSelect } from '@wordpress/data';

function BookPanel() {
    const postType = useSelect( ( select ) =>
        select( 'core/editor' ).getCurrentPostType()
    );
    const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );

    return (
        <PluginDocumentSettingPanel name="book-details" title="Book details">
            <TextControl
                label="ISBN"
                value={ meta.isbn || '' }
                onChange={ ( value ) => setMeta( { ...meta, isbn: value } ) }
            />
        </PluginDocumentSettingPanel>
    );
}

registerPlugin( 'acme-book-panel', { render: BookPanel } );

With this approach there is no save_post handler and no nonce of your own: the editor saves the meta through the REST API, which checks authentication and the auth_callback and runs your sanitize_callback. Tooling for such panels is covered in building blocks: an overview. Meta boxes remain the fastest way to add a field for classic and block editors alike; sidebar panels are the better choice when you can build JavaScript.

Common mistakes

  • Saving without a nonce check. Anyone could trick a logged-in editor into changing data.
  • Skipping the autosave and capability checks. Data is erased or changed by the wrong user.
  • Printing stored values unescaped. Use esc_attr() in attributes and esc_html() in text.
  • Trusting $_POST directly. Unslash, sanitize and validate each field.
  • Forgetting that missing checkboxes are absent from the request. Treat "not present" as "off" only when your form was submitted.
  • Not registering the type. save_post_book never fires if the post type is spelled differently.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why must a save_post handler check for autosaves?

    WordPress autosaves in the background and the request does not carry your fields. Without the check, your handler would overwrite good data with empty values.
  2. 2. What does a nonce prove?

    A nonce protects against forged requests. It is not a permission check, so you still need current_user_can().
  3. 3. Which hook registers a meta box?

    add_meta_boxes fires when the edit screen is being prepared. add_meta_box() belongs inside that callback.
  4. 4. When should you call wp_unslash() on $_POST values?

    WordPress slashes superglobals. Unslash first, then sanitize and validate.
  5. 5. How does the block editor save classic meta boxes?

    The editor saves the post through REST and then submits the meta box forms in a follow-up request, so the save_post pattern still works.

Summary

  • A meta box is a panel on the edit screen, registered with add_meta_box() on add_meta_boxes.
  • Render a nonce field first, then your inputs with escaped current values.
  • On save_post_{type}, check the nonce, autosave, revision and capability, then unslash, sanitize, validate and save.
  • A nonce is not a permission check, and a capability check is not a nonce check: you need both.
  • The block editor shows meta boxes below the content and saves them separately; sidebar panels backed by register_post_meta() are the modern alternative.
  • The runnable code is a stand-in that models the order of the checks.

Next: Permalinks and Rewrite Rules