The Metadata API – when an option doesn’t work

Yesterday, we took a look at the Options API. I also explained when it’s worth using it and when it’s best not to use it. One point I mentioned was adding additional data to posts, pages, and users. And that’s exactly where the Metadata API comes in – it’s designed specifically for this purpose. Some of you may also know it as “Custom fields” from pages and posts. So let’s take a closer look at it, because it can do more than just pages and posts.

What does the API do?

Much like the Options API, it stores key-value pairs – but not for the WordPress installation as a whole, rather for a specific object. Such an object can be a post, a page, a custom post type, a user, a comment, or even a category, a tag, or a custom taxonomy. A site in a multisite network can have metadata, too. If you look in the database, you’ll find several tables ending in meta: wp_postmeta, wp_usermeta, wp_commentmeta and wp_termmeta, and in a multisite also wp_blogmeta and wp_sitemeta. The columns are almost the same in all tables. The first column is usually called meta_id (except for the wp_usermeta table, where this column is called umeta_id for historical reasons). The second column is named according to the object type – for example, post_id, user_id, comment_id, etc. The last two columns have the same names in all tables: meta_key and meta_value. So, much like the options table, it’s a simple “key-value store,” except that it’s linked to an object.

Unlike with options, however, a key can appear multiple times for the same object. When reading the data, you can then decide whether you want only one value for a key or all of them.

Just like with options, objects and arrays are automatically serialized in the Metadata API. Scalar values, on the other hand, are returned as strings.

Which functions should I know?

The functions are also very similar to those in the Options API. For example, we use get_post_meta() to retrieve metadata, add_post_meta() to add it for the first time, update_post_meta() to update it, and delete_post_meta() to delete it.

The get_post_meta() function has an optional third parameter $single. If we set this to true, we receive only a single value. Otherwise, by default, we receive an array of metadata for the given $key.

The situation is very similar with the optional fourth parameter $unique in add_post_meta(). If we do not set this to true, the function creates another value with the same key. This is the default behavior and can lead to real problems. On success, the function returns the value of meta_id.

A special feature of update_post_meta() is the optional fourth parameter $prev_value. If this is specified, only the (duplicate) values with this previous value are updated. If it is omitted, all values with that key are overwritten. By the way, if there’s no value yet, update_post_meta() simply creates it. So you only really need add_post_meta() if you deliberately want to store multiple values.

Similarly, with delete_post_meta(), the optional third parameter $meta_value ensures that only the entry with that specific value is deleted; if the parameter is omitted, all entries with that key are deleted.

It can all be a bit confusing if you’ve never encountered a situation where there were multiple values per meta key. But it happens faster than you think – you might accidentally create multiple values.

I’ve only mentioned the *_post_meta() functions so far. However, the Metadata API behaves exactly the same way for all other objects. So simply replace post in the function names with the object you want to modify.

There are also generic functions like get_metadata(), add_metadata(), etc., where you specify the object type in the first parameter. This is useful whenever you first decide dynamically in your code which object you want to attach metadata to.

You can use the metadata_exists() function to check whether an object has a specific metadata entry. The function distinguishes between missing and empty values and ignores registered default values. That’s handy if you register a default value, as we’ll do in a moment: get_post_meta() then returns a 0 even without a stored value, but metadata_exists() returns false.

Using functions like register_meta() (specifying the object type), register_post_meta(), register_term_meta(), etc., you can register metadata for objects in a similar way to how we used register_setting() in our example from Day 3.

What does this look like in practice?

Let’s expand our plugin from the past few days a little further. Each post represents a “door” in an advent calendar, and that’s exactly what we want to store as a number associated with the post. The number is registered and included in the response from the Day 1 REST endpoint. The code for registration looks like this:

function advent_calendar_register_meta() {
	register_post_meta(
		'post',
		'advent_calendar_day',
		[
			'type'              => 'integer',
			'label'             => __( 'Advent calendar day', 'advent-calendar' ),
			'single'            => true,
			'default'           => 0,
			'sanitize_callback' => 'absint',
			'show_in_rest'      => [
				'schema' => [
					'minimum' => 0,
					'maximum' => 24,
				],
			],
		]
	);
}
add_action( 'init', 'advent_calendar_register_meta' );

Our callback function runs on init because we need it in both the backend and the frontend. We set single to true because each post appears on only one day. The label ends up as the title in the field’s REST schema, so the Block Editor, for example, can show a readable name instead of the key. With a default value of 0, we can express that a post doesn’t belong to a door (yet). The sanitize_callback makes sure that we only store positive whole numbers or 0. But be careful: absint() turns -7 into 7, not into 0. By the way, the callback doesn’t only run for REST requests, but whenever we use add_post_meta() or update_post_meta(). To be more precise, it’s called in sanitize_meta(). The schema inside show_in_rest only validates values that come through the REST API, but not values that are set with update_post_meta(), for example.

Now we want to return the newly stored value in the REST response as well. To do this, we only need to add one additional line to the advent_calendar_get_post() function:

return rest_ensure_response(
	[
		'id'      => $post->ID,
		'day'     => (int) get_post_meta( $post->ID, 'advent_calendar_day', true ),
		'title'   => get_the_title( $post ),
		'link'    => get_permalink( $post ),
		'date'    => get_post_time( 'c', true, $post ),
		'excerpt' => wp_trim_words( $content, max( 1, $excerpt_length ) ),
	]
);

We have to set the third parameter to true here, even though we specified during registration that there should only be a single value, because otherwise the function would still return an array containing that single value. We also have to cast the value to (int) because scalar values are always returned as strings. Only if no value has been stored yet, we get the registered default, and that’s already an integer in our case. But the cast doesn’t hurt.

By the way, if we use the Core endpoint for posts instead of our own REST endpoint, we don’t have to do anything at all, because with show_in_rest in the registration, the value is automatically included in the meta field. This requires the post type to support custom-fields, which is the case for posts.

You can set the value for a post in the Block Editor with the “Custom fields” (you have to enable them first under “Preferences → General → Advanced”) or quickly on the command line: wp post meta update 5 advent_calendar_day 5.

Another important use case for metadata is search. For example, if we want to create a new REST endpoint that allows us to retrieve the post for a specific day, or program a frontend search for it, we can find the post as follows:

$posts = get_posts(
	[
		'tag'            => advent_calendar_get_settings()['tag'],
		'posts_per_page' => 1,
		'meta_key'       => 'advent_calendar_day',
		'meta_value'     => 5,
		'meta_type'      => 'NUMERIC',
	]
);

It’s exactly this ability to query metadata that makes it so powerful and versatile. However, it’s important to note that there is no index on meta_value. A search on this field is therefore “expensive,” which is why people often warn against such queries and recommend using taxonomies instead. Sorting by this value is also not particularly efficient. By the way, with 'meta_type' => 'NUMERIC' from our example, the database compares the values as numbers and not as strings. But to do that, it has to convert every value first, which makes the query even a bit more expensive.

If we want to delete all metadata with a specific key for all entries, for example when our plugin is uninstalled, we can add one line to yesterday’s uninstall.php:

<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

delete_option( 'advent_calendar_settings' );
delete_option( 'advent_calendar_version' );
delete_post_meta_by_key( 'advent_calendar_day' );

Apart from posts, such a function only exists for sites in a multisite (delete_site_meta_by_key()). For all other object types, we use delete_metadata() and set the optional fifth parameter $delete_all to true.

However, you don’t necessarily always have to clean up metadata manually. If you permanently delete a post (or another object with metadata), the metadata is automatically deleted as well. If a post only goes to the trash, its metadata stays.

What should I watch out for?

The most common mistake when working with the Metadata API is probably forgetting the $single parameter and then suddenly getting an array instead of a scalar value. And as mentioned earlier, scalar values are always returned as strings, so they may need to be cast.

Contrary to what the name might suggest, the $unique parameter also does not guarantee that the value won’t appear twice in the database. It only prevents a post – in our example – from being assigned two door-number values. However, it doesn’t prevent us from accidentally assigning the same number to two posts.

If you prefix the key with an underscore, the metadata will not be displayed in the custom fields and can only be written via the REST API using an auth_callback. So that’s what you should use for “internal metadata”.

And while we’re on the subject of internal data and the REST API: all metadata marked with show_in_rest is visible to anyone who can read the object. So be careful what you include in the REST responses.

As mentioned earlier, database queries involving metadata are “relatively expensive,” so use them deliberately. If you only need to output them, that’s no problem at all. However, searching or sorting based on them can significantly impact performance.

Having multiple values for the same metadata field can sometimes make sense, but in the vast majority of cases, you’ll only want to store a single value. So be sure to always set the parameters in the various functions so that you only read, write, update, or delete a single value.

As with options, you better not store huge amounts of data in metadata. Since all metadata for all post types ends up in a single table, it can quickly become very large. For this reason, WooCommerce introduced HPOS as an alternative storage for orders.

Metadata is also not normally versioned in revisions, but you can enable this with 'revisions_enabled' => true in the registration – provided the post type itself supports revisions.

When should I use it?

If data belongs to exactly one object and can’t be stored in the content itself, then metadata is a good place for it. An e-commerce platform like WooCommerce is certainly a good example here, because products have a lot of “attributes”, which are still stored as metadata today. Only for orders, WooCommerce now uses its own tables with HPOS.

But additional data for users, taxonomies, or comments are also common use cases. The Antispam Bee plugin, for example – which I also help develop – stores in the metadata the reason a comment was marked as spam.

If, on the other hand, you want to store values for your entire WordPress installation, the options we covered yesterday are worth considering.

If you want to filter, sort, or group by values, other alternatives – such as a custom taxonomy – might also be a better approach. And last but not least, you shouldn’t store overly large objects in the metadata table. So, if necessary, create separate tables for this purpose, just as WooCommerce does with HPOS for orders.

Similarly to options, you better not store temporary or constantly changing data as metadata either.

In general, use metadata for data that is only displayed, taxonomies for values used for searching, filtering, or grouping, and separate tables for more complex data or large data sets.

Where can I find more information?

What should I remember?

  1. Metadata is attached to exactly one object – posts, users, comments, and terms all use the same API.
  2. Use register_post_meta() to define the type, default value, sanitization, and REST visibility all in one place.
  3. Use $single, $unique, and $prev_value to decide whether to work with one or multiple values.
  4. Filtering and sorting by meta values is expensive – so think carefully about your data model before you save any data.

Tomorrow is St. Nicholas Day, and I’ve brought you a slightly different API – but one that’s no less important for a WordPress installation.

Leave a Reply

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