Skip to content
Tutorials Center
My learning

Topics

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

Custom Fields and Post Meta

Store extra data on posts with post meta: add, update and get_post_meta, single vs array values, register_post_meta for REST and sanitizing, protected keys.

A post has a title, content, an excerpt and a status. A book needs an ISBN and a page count; an event needs a date and a venue; a product needs a price. WordPress stores such extra values as post meta, also known as custom fields. Each piece of meta is a key and a value attached to one post, saved in the wp_postmeta table.

Post meta is the most common way to extend content, and it is easy to start with. It is also where many sites pick up slow queries and security holes, because the values come from users and the table has a particular shape. This lesson covers the basic functions, single versus array values, protected keys, register_post_meta() for REST and sanitizing, and how native meta compares with field plugins such as ACF.

Real post meta functions only run inside WordPress, so the real code below is read-only. The runnable examples are plain-PHP stand-ins that copy the return values and rules. They are simplified models, not core code.

The four basic functions

PHP
<?php
$post_id = 42;

// Create a value. The 4th argument makes the key unique for this post.
add_post_meta( $post_id, 'isbn', '978-1-23456-789-7', true );

// Create or change a value.
update_post_meta( $post_id, 'page_count', 320 );

// Read it. The third argument asks for a single value.
$pages = get_post_meta( $post_id, 'page_count', true );   // "320"

// Remove it.
delete_post_meta( $post_id, 'page_count' );

Each function takes the post ID first, then the key. What they return matters:

  • add_post_meta() returns the new meta ID, or false if the key is unique and already exists.
  • update_post_meta() returns the new meta ID when it had to create the row, true when it changed the value, and false when the value was already the same or the update failed. Do not treat false as an error without checking.
  • get_post_meta() with $single set to true returns the value, or an empty string if the key does not exist. With $single left at false it returns an array of every value stored under that key, which is empty when there are none.
  • delete_post_meta() returns true if something was removed.

Inside a Loop, get_post_meta( get_the_ID(), 'isbn', true ) is how a template reads a field. Escape it when you print it, because meta values are just text that someone typed: echo esc_html( $isbn );. See escaping output.

flowchart LR
    A["update_post_meta(42, 'isbn', ...)"] --> B["wp_postmeta row:<br/>post_id 42, key isbn, value ..."]
    B --> C["get_post_meta(42, 'isbn', true)"]
    C --> D["String returned to the template"]

A meta value is one row in wp_postmeta, keyed by post ID and meta key.

Everything is a string

The meta_value column holds text. When you save a number, you get a string back ("320", not 320). When you save an array or object, WordPress serializes it into a PHP serialization string and unserializes it again on read. That is convenient, but you cannot search inside a serialized array with SQL, and you should never store data from untrusted sources as serialized objects. For anything you want to filter or sort by, store one simple value per key. Meta queries explains the cost of searching meta, and the schema lesson shows why: one row per value is flexible, but joins on it get slow.

Values are also passed through wp_unslash() when saved. If you store JSON that contains backslashes, wrap it with wp_slash() first, or the backslashes will be stripped.

Single or multiple values

One post may hold several rows with the same key. That is how a post can have two author_email values or many gallery_image IDs. add_post_meta() without the unique flag appends a new row each time. get_post_meta() then needs the $single argument to decide the shape:

PHP
<?php
add_post_meta( 42, 'tag_line', 'First' );
add_post_meta( 42, 'tag_line', 'Second' );

get_post_meta( 42, 'tag_line' );         // [ 'First', 'Second' ]
get_post_meta( 42, 'tag_line', true );   // 'First'

update_post_meta() with no previous value changes every row for that key to the new value, so use it for keys that are meant to be single. Use add_post_meta() for repeating keys.

Protected keys

A key that starts with an underscore is protected. WordPress hides it from the Custom Fields box in the classic editor and refuses to let the REST API or the UI change it unless you allow it. Core uses protected keys for its own data, such as _thumbnail_id and _edit_lock. Use the same convention for plugin data that editors should not touch by hand, for example _acme_internal_score.

Protected does not mean secret or safe. Any code can read or write protected keys. If you need a rule such as "only editors may change this over REST", register the meta with an auth_callback as shown below. The is_protected_meta() function tells you whether a key counts as protected.

A meta store you can run

This stand-in keeps rows in a list the way wp_postmeta does: one row per value, with a meta ID. It copies the return values of the real functions and the single-or-array shape of get_post_meta().

PHP A post meta store with single and array reads

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.

Notice the add() with the unique flag failing the second time, and the three update() calls: the first creates the row and returns its ID, the second returns false because nothing changed, and the third returns true. The underscore key _acme_score is stored but missing from the visible list.

register_post_meta(): describing your fields

Plain update_post_meta() works without any setup. register_post_meta() adds a description of the field that WordPress can use for sanitizing, permissions and the REST API. Call it on init:

PHP
<?php
function acme_register_book_meta(): void {
    register_post_meta( 'book', 'page_count', [
        'type'              => 'integer',
        'single'            => true,
        'default'           => 0,
        'description'       => 'Number of pages',
        'show_in_rest'      => true,
        'sanitize_callback' => 'absint',
        'auth_callback'     => static function (): bool {
            return current_user_can( 'edit_posts' );
        },
    ] );
}
add_action( 'init', 'acme_register_book_meta' );

What each part does:

  • type is one of string, boolean, integer, number, array or object. It is mainly the schema for REST requests, which validate and convert values. In plain PHP, get_post_meta() still gives you what is stored, which is normally a string, so cast when you need a number.
  • single says whether the key holds one value, which changes the shape used by REST.
  • default is returned by get_post_meta() when the key has no value yet.
  • sanitize_callback runs on every save, whether it comes from your own code, the REST API or the editor. The value is the first argument. It is the central place to clean input. See sanitizing and validating input.
  • auth_callback decides who may change the meta through the REST API and the UI, which matters most for protected keys.
  • show_in_rest exposes the field in /wp/v2/book under a meta object. The post type must list custom-fields in its supports array for this to work (see custom post types). Block editor plugins rely on this to read and write fields.

Registered meta also becomes the basis for block bindings, which let a block show a meta value.

Typed registration you can run

This stand-in applies a registered definition: it falls back to the default, runs the sanitize callback on writes, and casts for a REST-style read.

PHP Typed meta registration with sanitizing and defaults

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.

The sanitize function runs at write time, so by the time you read the values they are clean. Remember what this stand-in leaves out: real sanitize callbacks like absint() and sanitize_text_field() do more than these arrow functions, and strip_tags() leaves the text inside <script> behind, which is why real code uses WordPress's own sanitizers.

Native meta or a fields plugin?

Plugins such as Advanced Custom Fields (ACF) give editors a field builder, repeaters, galleries and conditional logic without code. They still save into the same wp_postmeta table, usually with an extra hidden key that remembers the field's definition, and give you helper functions such as get_field(). Native meta needs more PHP, but it has no dependency and no learning curve for your team, and your data stays readable if the plugin is removed.

A practical rule: use native meta and register_post_meta() for a few simple fields on a plugin you distribute; consider a fields plugin for client sites with many editable layouts. The next lesson shows how to build an editing screen for your own fields: meta boxes and saving data.

Common mistakes

  • Reading meta as the wrong type. get_post_meta() returns strings (or arrays when $single is false).
  • Forgetting the third argument. Without true you get an array, even for one value.
  • Storing searchable data in a serialized array. Use one key per value you will query.
  • Printing without escaping. Meta is user input.
  • Using many meta values for a heavy query. Meta is flexible, not fast; see performance optimization.
  • Not registering fields exposed to REST. Without show_in_rest and custom-fields support, the editor cannot see them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does get_post_meta( $id, 'tag_line' ) return when the third argument is omitted?

    Without $single set to true, get_post_meta() returns an array of values, which is empty when the key has none.
  2. 2. What does update_post_meta() return when the new value equals the stored value?

    When nothing changes it returns false. True means a changed value, and a meta ID means a new row was created.
  3. 3. What does a leading underscore in a meta key mean?

    Protected keys are hidden from the classic Custom Fields box and not editable through the UI or REST unless allowed. They are still readable by any code.
  4. 4. Which post type setting is needed so registered meta shows in the REST API?

    show_in_rest on the meta registration is needed, and the post type must support custom-fields for the REST API to include meta.
  5. 5. Where should you clean a meta value so every route into the database is covered?

    The sanitize_callback runs on every save, including REST and editor saves, so the stored value is clean.

Summary

  • Post meta stores key and value pairs per post in wp_postmeta.
  • add_post_meta(), update_post_meta(), get_post_meta() and delete_post_meta() do the work; mind their return values.
  • Values are strings; arrays are serialized. Store one simple value per key when you need to query it.
  • get_post_meta() with $single true returns one value, otherwise an array.
  • Keys that start with an underscore are protected from the Custom Fields box, not hidden from code.
  • register_post_meta() adds type, default, sanitizing, permissions and REST exposure.
  • ACF-style plugins build on the same table; native meta has fewer dependencies.
  • The runnable examples are stand-ins that model the rules.

Next: Meta Boxes and Saving Data