← All posts

WordPress custom fields without ACF: meta boxes, register_post_meta() and saving data securely

Add a field to your posts or a custom post type without a plugin: register the meta, build the meta box, save it safely, display the value, and avoid the usual traps (checkboxes, autosave, the block editor).

WordPress custom fields without ACF: meta boxes, register_post_meta() and saving data securely

Key points

  • For a handful of simple fields, register_post_meta() plus a meta box is enough: no plugin dependency, and the code is versioned with your theme or custom plugin.
  • The save routine must check the nonce, autosave and capabilities, then sanitise the value. That’s where most vulnerabilities hide.
  • Always escape on output, and don’t build heavy filtering on unindexed meta values.

Advanced Custom Fields is a great tool, and we use it on projects with dozens of fields and complex layouts. But for two or three fields (a source URL, a subtitle, a “featured” checkbox), adding yet another plugin creates a dependency for very little: deactivate it by mistake and the fields vanish from the admin, and the template that displays them may start throwing errors. Writing those fields yourself takes about a hundred lines, as long as you follow a few security rules that copy-pasted snippets usually skip. Here’s the complete pattern we use, with a “source URL” field on posts as the example.

Register the meta with register_post_meta()

Many tutorials skip this step and jump straight to the meta box. That’s a shame: registering the meta tells WordPress its type, default value, how to sanitise it and who may change it. It’s also what makes it available in the REST API, and therefore in the block editor.

add_action( 'init', function () {
    register_post_meta( 'post', 'wts_source_url', [
        'type'              => 'string',
        'single'            => true,
        'default'           => '',
        'show_in_rest'      => true,
        'sanitize_callback' => 'esc_url_raw',
        'auth_callback'     => function ( $allowed, $meta_key, $post_id ) {
            return current_user_can( 'edit_post', $post_id );
        },
    ] );
} );

A few choices worth understanding:

  • single => true: one value per post. Without it, get_post_meta() returns an array, a common cause of display bugs.
  • sanitize_callback: runs on every write through update_post_meta(), REST API included. The value gets cleaned even when someone bypasses your form.
  • auth_callback: controls who can change the value through the REST API. WordPress applies a cautious default for keys starting with an underscore, but being explicit is better.
  • The wts_ prefix avoids collisions with a plugin that might use a generic key such as source.

For a custom post type, replace 'post' with its slug, and make sure it’s registered with 'supports' => [ 'custom-fields' ] if you want the meta exposed in the REST API: without that, show_in_rest has no effect.

A meta box, and a save routine that lets nothing slip

The meta box shows the field on the edit screen. It works in the block editor too, which displays it in a panel below the content, or in the sidebar with the side context. The save routine is where your attention should go.

add_action( 'add_meta_boxes', function () {
    add_meta_box( 'wts_source', 'Article source', 'wts_source_box', 'post', 'side' );
} );

function wts_source_box( WP_Post $post ): void {
    wp_nonce_field( 'wts_source_save', 'wts_source_nonce' );
    $url = get_post_meta( $post->ID, 'wts_source_url', true );
    ?>
    <p>
        <label for="wts_source_url">Source URL</label>
        <input type="url" id="wts_source_url" name="wts_source_url"
               value="<?php echo esc_attr( $url ); ?>" class="widefat">
    </p>
    <?php
}

add_action( 'save_post_post', function ( int $post_id ) {
    if ( ! isset( $_POST['wts_source_nonce'] )
        || ! wp_verify_nonce( $_POST['wts_source_nonce'], 'wts_source_save' ) ) {
        return;
    }
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }
    if ( wp_is_post_revision( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $url = isset( $_POST['wts_source_url'] )
        ? esc_url_raw( wp_unslash( $_POST['wts_source_url'] ) )
        : '';

    if ( $url === '' ) {
        delete_post_meta( $post_id, 'wts_source_url' );
    } else {
        update_post_meta( $post_id, 'wts_source_url', $url );
    }
} );

Each of the four checks in the save routine is there for a reason:

  • The nonce proves the request comes from your form in the admin, not from a third-party page tricking a logged-in admin into submitting it (CSRF). It also stops the value being wiped when the post is saved through another route (Quick Edit, the REST API) where your field isn’t sent.
  • Autosave: WordPress regularly saves an automatic draft; without this check your code could process a partial save.
  • Capabilities: edit_post checks that the user can edit this post, which is more precise than checking a role.
  • Sanitising: wp_unslash() removes the slashes WordPress adds to incoming data, then esc_url_raw() keeps only a valid URL.

We hook into save_post_post (the save_post_{type} form) rather than save_post: it only fires for the right post type, which saves a check and avoids running code every time a page or menu is saved.

Finally, when the field is cleared we delete the meta instead of storing an empty string. The database stays tidy, and an EXISTS check in a query returns the right result.

Displaying the value and querying on it

On output the rule is simple: escape late, according to context. esc_url() for an href, esc_html() for text, esc_attr() for other attributes. Even a value sanitised on save must be escaped: it may have been changed directly in the database, by an import or by another plugin.

// In single.php or a dynamic block
$url = get_post_meta( get_the_ID(), 'wts_source_url', true );
if ( $url ) {
    printf(
        '<p class="source">Source: <a href="%s" rel="noopener">%s</a></p>',
        esc_url( $url ),
        esc_html( wp_parse_url( $url, PHP_URL_HOST ) )
    );
}

To list posts that have a source, a meta_query does the job:

$q = new WP_Query( [
    'post_type'      => 'post',
    'posts_per_page' => 10,
    'meta_query'     => [
        [ 'key' => 'wts_source_url', 'compare' => 'EXISTS' ],
    ],
    'no_found_rows'  => true,
] );

One caveat: the wp_postmeta table indexes the key, not the value. Filtering or sorting on a meta value is fine with a few hundred posts but gets slow on sites with tens of thousands of entries, especially with several combined conditions. On our projects, as soon as a field is used for filtering (a price, a city, a business category) we turn it into a taxonomy or, at larger volumes, a column in a dedicated table.

The traps we hit on every project

An unticked checkbox isn’t sent. Browsers send nothing for an unchecked box. If your code does nothing when the key is missing from $_POST, the box can never be unticked. Treat a missing key as false, after verifying the nonce (which guarantees the form really was submitted).

Keys starting with an underscore. A key like _wts_source_url is treated as protected and doesn’t appear in the native “Custom Fields” panel. Handy to avoid double entry, confusing if you don’t know the rule.

Revisions. By default meta isn’t part of revisions: restoring an old version of a post doesn’t restore the field. Since WordPress 6.4, passing 'revisions_enabled' => true to register_post_meta() includes it, provided the post type supports revisions.

The block editor and meta boxes. Meta boxes work, but the editor saves them in a separate request after the post itself. If you want a field fully integrated into the sidebar, the modern route is a small JavaScript panel (PluginDocumentSettingPanel) that reads and writes the meta through show_in_rest. It’s more work; for most sites the meta box remains a sensible choice.

Where to put this code. Not in the functions.php of a theme you might replace: the data would stay in the database but the interface would disappear. A small custom plugin or a file in mu-plugins is a better home.

FAQ

When is ACF still the better choice?

When there are many fields, repeatable ones (testimonials, opening hours), or fields edited by non-developers who need a polished interface. ACF brings UI, a wide range of field types and validation that would be costly to rebuild.

Can I add this field to pages and custom post types?

Yes: call register_post_meta() and add_meta_box() for each post type (add_meta_box accepts an array of screens) and use the matching save_post_{type} hook, or save_post with a post type check.

My values disappear after a Quick Edit. Why?

Most likely because the save routine doesn’t check the nonce and treats a missing field as an empty value. Quick Edit doesn’t send your fields, so without a nonce check your code wipes the value. Putting the nonce check first fixes it.

Need custom fields, a bespoke content type or a review of your WordPress code? We build clean, maintainable custom plugins. Let’s talk about your project.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →