The Options API – store data permanently and retrieve it easily
Yesterday, we looked at the Settings API, which lets us create our own settings pages. Our settings were saved in the wp_options table via the options.php file. And that’s exactly what today is about: options.
Options don’t necessarily always have to come from a settings page. A plugin can also use them on its own, for example, to keep track of which plugin version has already been migrated or whether a specific admin message has already been displayed. So even if your plugin doesn’t include a settings page, options could still be useful for your plugin. I use the API in a lot of my plugins.
But even though the API seems very simple, there are a few things to keep in mind when using it, which I’ll briefly go through below.
What does the API do?
Simply put, the API stores key-value pairs in the wp_options table in the database. The table has only a few columns: option_id, option_name, option_value, and autoload. The table is intended for all settings that you want to permanently store in the database for your plugin or theme. WordPress itself uses this table a lot. Among the most important entries here are probably siteurl, home, and blogname. But most other WordPress Core settings that you configure in the backend are also stored in this table.
If objects or arrays are stored, WordPress automatically serializes them. This makes working with the API much easier, but it can also cause problems if you want to update values directly in the database.
The API also has built-in caching: Each option is stored in the cache after it’s first read, so any subsequent calls within the same request no longer require a database query. You can also use the autoload value to specify whether your option should be preloaded along with all other options every time a page is loaded. But be warned! What sounds great can seriously hurt your site’s performance if you’re not careful.
The Options API is therefore intended for site-wide settings, but not for settings or options specific to a post, page, or user. There are other APIs for that.
Which functions should I know?
The most important function is probably get_option(), which returns the option_value for an option_name. An optional second parameter can be used to specify a default value if no value is found in the database. If you’ve set a default using register_setting(), that value will be returned if you don’t pass your own default and the setting is registered in the current request.
The second most important function is update_option(), which allows us to update the value of an option. If we’re creating the option for the first time, we can do so with add_option(). Both functions have an optional autoload parameter that specifies whether our option should be loaded on every page view. Since WordPress 6.6, the default value has been null. WordPress then decides on its own and automatically loads only options up to about 150 KB. Previously, every option was automatically loaded by default, which could cause big performance problems. So please think carefully about whether your option really needs to be loaded every time. In most cases, this won’t be necessary. You can adjust the autoload values later using wp_set_options_autoload() or wp_set_option_autoload_values() without changing the option’s value.
Finally, there’s the delete_option() function, which lets you delete an option from the table. These are the basic functions you’ll be working with.
If you want to retrieve multiple options at once in a single database query, you can use get_options().
If you’re working with a multisite installation, you can store network-wide options in the wp_sitemeta table using get_site_option(), update_site_option(), and delete_site_option(). The functions get_network_option(), update_network_option(), and delete_network_option() work the same way but also require a network ID. Use get_blog_option() to retrieve an option from another site in the network.
And there are lots of hooks that allow you to modify values or trigger an action when saving or retrieving them.
What does this look like in practice?
Let’s continue working on yesterday’s plugin. We’ve already used the advent_calendar_settings option. Today, we’ll tackle everything on the settings page that has to do with options: central default values, initialization on activation, a small migration, and cleanup on uninstall. In doing so, we’ll intentionally give two options different autoload behaviors.
Let’s start with the central default values. In yesterday’s code, we had hard-coded the default settings in three different places. We can now define these in a single, central location:
function advent_calendar_get_default_settings() {
return [
'tag' => 'wordpress-api-adventskalender',
'excerpt_length' => 30,
];
}
function advent_calendar_get_settings() {
$settings = get_option( 'advent_calendar_settings', [] );
if ( ! is_array( $settings ) ) {
$settings = [];
}
return wp_parse_args( $settings, advent_calendar_get_default_settings() );
}
Our new function advent_calendar_get_default_settings() always returns the default values, in case we need them anywhere else in the code. Here in the example, that’s within the advent_calendar_get_settings() function.
By the way, we can’t simply use the default array from register_setting() that we used yesterday. Since we only register the setting in admin_init, it wouldn’t be available to us in the REST endpoint.
With wp_parse_args(), we can fill in missing keys if, for example, an older array was still stored in the database that didn’t yet contain all the values. In that case, the default values would be added accordingly.
We’ll now use these two functions wherever hard-coded values were previously used: In the REST endpoint, we’ll replace the call to wp_parse_args() with advent_calendar_get_settings(), and the two render callbacks for the fields will also retrieve their values from there. For the default in register_setting() and the fallback values in the sanitize callback, we use advent_calendar_get_default_settings().
To initialize our default values when the plugin is activated – so they’re already in the database on the very first call – we use register_activation_hook() for our plugin:
register_activation_hook( __FILE__, 'advent_calendar_activate' );
function advent_calendar_activate() {
add_option(
'advent_calendar_settings',
advent_calendar_get_default_settings(),
'',
false
);
}
We use add_option() here instead of update_option() so that settings that were already changed aren’t overwritten with the default values when the plugin is reactivated. The empty string as the third parameter hasn’t been used for a long time, but we still need to pass it to get to the autoload parameter. We set the autoload value to false because our option is only needed in the REST endpoint and not on every request.
If you ever change any of your plugin’s options, you should write a “migration” for it. It’s common practice to store a “plugin version” in an additional option for this purpose. So let’s assume we initially had only one option with a single value, which we later replaced with an array containing multiple values. In that case, a migration might look something like this:
define( 'ADVENT_CALENDAR_VERSION', '1.1.0' );
function advent_calendar_maybe_upgrade() {
$version = get_option( 'advent_calendar_version', '1.0.0' );
if ( version_compare( $version, ADVENT_CALENDAR_VERSION, '>=' ) ) {
return;
}
if ( version_compare( $version, '1.1.0', '<' ) ) {
$settings = advent_calendar_get_settings();
$settings['tag'] = get_option( 'advent_calendar_tag', $settings['tag'] );
update_option( 'advent_calendar_settings', $settings, false );
delete_option( 'advent_calendar_tag' );
}
update_option( 'advent_calendar_version', ADVENT_CALENDAR_VERSION, true );
}
add_action( 'plugins_loaded', 'advent_calendar_maybe_upgrade' );
Here, we first check whether the migration has already taken place – that is, whether the version is greater than or equal to the constant – and then exit the function. If it hasn’t run yet, we run it. On a new installation, the advent_calendar_version option doesn’t exist yet, so we use 1.0.0 as the default value. This means the migration also runs once on a new installation. But that’s not a problem, because without the old advent_calendar_tag option, the default value simply remains unchanged. We could also have multiple “migration paths” if the plugin has skipped several version updates at once and multiple migrations need to run one after another. At the very end, if everything was successful, we set the version in the database to the current value.
Did you notice that we set the autoload value for the version to true? That’s because this migration function is executed on every request, rather than in the activation hook. It wouldn’t work there, since the activation hook isn’t executed during a plugin update. That’s exactly why it makes sense to always load the option. However, the plugin’s actual options in advent_calendar_settings are still only read when needed.
You may also have noticed that we don’t use add_option() to set the initial value. If an option doesn’t exist yet, it’s created using update_option(). And since we always want to save the current value and overwrite any existing value, this works without any issues.
Finally, here’s a quick example of how we can clean up options. To do this, we simply create an uninstall.php file in the plugin with the following content:
<?php
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
delete_option( 'advent_calendar_settings' );
delete_option( 'advent_calendar_version' );
We don’t need a hook here, because the uninstall.php file (if present) is automatically executed by WordPress Core when a plugin is uninstalled.
Options with autoload in particular should always be removed from the database when the plugin is deleted. You shouldn’t do this when simply deactivating the plugin, because otherwise all settings will be lost, which is probably not what you want.
What should I watch out for?
One of the most important points is probably choosing the right setting for autoloading. For options like the plugin version, you should set the value to true; for almost all other options, false is likely the better choice.
You can change the autoloading value later either by saving the option again with update_option() (if the value stays the same, the autoload value doesn’t change either) or by using functions like wp_set_option_autoload().
Also consider what you’re storing in the options. For example, you shouldn’t store a single false value. That’s because get_option() returns false even if the option doesn’t exist at all. And update_option() won’t even create an option with the value false if it doesn’t already exist. While add_option() does create the option, it stores an empty string in the database – which you’ll get back starting with the next request if you don’t have a persistent object cache.
If your plugin has many settings, store them in an array. However, if you have an option whose value changes frequently – such as a counter – it’s better to use a separate option for it; otherwise, you’ll constantly be reading from and writing to a large array, and race conditions become more likely.
There’s also a maximum length of 191 characters for the option_name. And Site Health issues a warning as soon as all autoloaded options combined exceed 800 KB.
So it’s best to store only “relatively small” objects in options and move larger objects – and especially constantly changing values or even log entries – to their own tables or files. Sensitive data, such as API keys, are also better not stored as options, because they are stored in plain text in the database and thus end up in every backup or database export. If the option was registered with show_in_rest, it can also be read via the REST API (if the user has the right permissions).
When should I use it?
Options are ideal whenever you want to save site-wide settings for your plugin or theme. The Settings API, which we looked at yesterday, does exactly that. States such as the plugin version, feature flags, and similar information are a good fit as well.
Options are less suitable for large amounts of data, log entries, data related to posts, pages, or users, or other data for which WordPress has its own tables. Values that need to be filtered or sorted are also not well suited for storage in a key-value pair.
Data that’s only valid for a short time shouldn’t be stored as an option either, because the entries are permanently saved until they’re explicitly deleted.
And as mentioned earlier, sensitive data shouldn’t be stored in the options, even though this is still the case in practice for most plugins.
Where can I find more information?
- Options API
- Code Reference:
get_option() - Code Reference:
add_option() - Code Reference:
update_option() - Code Reference:
delete_option() - Code Reference:
wp_set_option_autoload() - Code Reference:
get_options() - Uninstall Methods
What should I remember?
- Options store site-wide settings as key-value pairs – arrays are automatically serialized.
- Set
autoloadtotrueonly if the value is really needed on every request; otherwise, set it tofalse. - Use
add_option()to initialize an option without overwriting it; useupdate_option()to change the existing value. - You should define default values in one place, save the plugin version for migrations, and remove options on uninstall.
The Options API is one of the most important APIs in WordPress. I hope the many warnings and restrictions about what not to use it for haven’t scared you off. The API is and remains essential for many plugins as well as WordPress Core. So be sure to give it a try in your plugins if you haven’t already.