Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 68 ยท Shortcodes, Options and Admin Pages

The Options API and Transients

Store settings and cached data in WordPress: get_option, update_option, autoload and its cost, serialized values, site options, and transients with expiry.

Almost every plugin needs to remember something: an API key, a color, the date of the last import. WordPress gives you a ready-made key-value store for this, the Options API. You give a value a name, save it, and read it back later from anywhere. Behind the scenes it is one database table, wp_options, which you met in The WordPress Database Schema.

A close relative is the Transients API, a key-value store for data that is allowed to disappear, such as the response of a slow remote request. This lesson covers both: how to read and write options, why the autoload flag matters for speed, how arrays are stored, how multisite changes the picture, and how transients expire.

The four basic functions

PHP
// Create an option only if it does not exist yet. Returns true or false.
add_option( 'nw_greeting', 'Hello' );

// Read it. The second argument is returned if the option is missing.
$greeting = get_option( 'nw_greeting', 'Hi there' );

// Create or change it. Returns true only if something changed.
update_option( 'nw_greeting', 'Welcome' );

// Remove it. Returns true if it existed.
delete_option( 'nw_greeting' );

Some details that decide whether your code is correct:

  • add_option() never overwrites. If the name exists, nothing happens and the call returns false.
  • update_option() creates the option when it is missing, and returns false when the new value equals the old one. A false return therefore does not always mean failure.
  • get_option() returns false for a missing option unless you pass a default. If false is a legitimate stored value, always pass a default you can tell apart.
  • Option names are strings up to 191 characters. Prefix them (nw_greeting, not greeting) so plugins do not clash. Store a group of related values in one array option rather than twenty separate rows.

You can also pass an option name to get_option() and receive values that WordPress itself keeps, such as blogname, admin_email or posts_per_page. Those live in the same table.

Arrays and serialization

An option value can be a string, number, boolean, array or object. WordPress stores everything as text in the option_value column. Arrays and objects are turned into a string with PHP's serialize() on the way in and restored with unserialize() on the way out. You never call these yourself:

PHP
update_option( 'nw_settings', array(
	'color'    => 'green',
	'per_page' => 12,
) );

$settings = get_option( 'nw_settings', array() );
echo $settings['per_page']; // 12

Because the whole array is one row, reading one key loads all of them, and updating one key means writing the entire array back. Keep option arrays small. Do not use options as a general database: if the data grows with the number of posts, users or orders, use post meta, a custom post type, or a custom table instead.

Never build serialized strings by hand and never unserialize() untrusted input. Serialized data stores string lengths, so editing it by hand or with a naive find-and-replace in SQL corrupts it. That is why tools such as WP-CLI's search-replace are aware of serialization.

Autoload and its cost

The wp_options table has a column called autoload. Rows marked to autoload are fetched in one query early in every request, and kept in memory so later get_option() calls cost nothing. Rows that are not autoloaded are fetched with a separate query the first time you ask for them.

flowchart TD
    R["Every request starts"] --> Q["One query:<br/>all autoload options"]
    Q --> M["Held in memory"]
    G1["get_option('blogname')"] --> M
    G2["get_option('nw_big_export')"] --> N{"autoload?"}
    N -->|"yes"| M
    N -->|"no"| D["Extra database query,<br/>on first use only"]

Autoloaded options are loaded for every page view; other options are loaded only when something asks for them.

This is convenient for small values you need on every page, and expensive for big ones. If a plugin stores a 400 KB array and marks it to autoload, every page view on the site, including pages that never use it, reads and unserializes it. A bloated autoloaded set is one of the most common causes of a slow WordPress admin.

You choose the flag when you create or update an option:

PHP
// Needed on every request: autoload is fine.
add_option( 'nw_version', '1.4.0', '', true );

// Big or rarely used: do not autoload.
update_option( 'nw_import_log', $big_array, false );

In update_option() the third argument is $autoload. Passing false (or 'no') stores the row as not autoloaded; passing nothing leaves the existing flag alone for an existing option. Recent WordPress versions can also decide automatically for very large values, but do not rely on that: set the flag deliberately. Rule of thumb: autoload small values read on most pages, and turn it off for anything large, anything read in only one admin screen, and anything that changes often.

The first TryIt is a stand-in option store with the same rules: add does not overwrite, update reports whether anything changed, arrays are serialized, and only autoloaded rows are counted when the "request" boots. It is plain PHP written for this site, not WordPress code.

PHP An option store with autoload

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.

Compare the query count before and after reading nw_import_log: the large option stays out of the boot query and only costs a lookup when something actually needs it.

Site options and multisite

On a single site, get_option() is all you need. On a multisite network (see Multisite Overview) each site has its own wp_options table, and there is a separate store for values shared by the whole network. You reach it with the *_site_option family: get_site_option(), update_site_option(), add_site_option() and delete_site_option(). On a normal single site these functions simply fall back to the ordinary options, so using them in a plugin meant for both setups is safe.

Transients: cached data with an expiry

A transient is an option that comes with a time to live. You store a value for a number of seconds and read it back until it expires:

PHP
$data = get_transient( 'nw_weather' );

if ( false === $data ) {
	$data = nw_fetch_weather_from_api(); // slow
	set_transient( 'nw_weather', $data, 15 * MINUTE_IN_SECONDS );
}

This is the cache-aside pattern: ask the cache, and on a miss compute the value and store it. WordPress defines the constants MINUTE_IN_SECONDS, HOUR_IN_SECONDS, DAY_IN_SECONDS, WEEK_IN_SECONDS and so on, so you never write 86400 by hand.

The rules to remember:

  • get_transient() returns false when the transient is missing or expired. If you need to cache false itself, wrap the value in an array.
  • An expiration of 0 means "no expiry", but the value can still be removed at any time, so never treat a transient as storage you can rely on.
  • Transient names are limited to 172 characters, which leaves room for WordPress's internal prefixes.
  • delete_transient( $name ) removes one early, which is how you invalidate a cache when the underlying data changes.
  • set_site_transient() and get_site_transient() are the network-wide versions.

Where transients live

By default a transient is stored as two options: _transient_nw_weather for the value and _transient_timeout_nw_weather for the expiry timestamp. Expired rows are not removed the moment they expire: WordPress checks the timeout when you read, and deletes the row then (plus some periodic cleanup).

If the site has a persistent object cache such as Redis or Memcached (see Caching and WP-Cron), transients go there instead and never touch wp_options. That is faster and keeps the table tidy, but it means transients can vanish whenever the cache server restarts or evicts entries. Your code must always cope with a miss.

The second TryIt simulates transients with a fake clock so the output is the same on every run. It implements the cache-aside pattern and counts how often the "slow" function actually runs.

PHP Transients with expiry

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 temperature changes only when the slow function runs again, so you can see exactly when the cache was used. Real transients behave the same way, except the clock is the real one.

Options or transients?

Question Use
Must the value survive forever (settings, version, API key)? Option
Is it a copy of data you can rebuild (remote response, expensive query result)? Transient
Is it large and read only occasionally? Option with autoload off, or a transient
Does it belong to one post or user? Post meta or user meta, not an option

Settings that users edit in the admin screens are usually saved through a structured layer on top of the Options API. That is the next topic: The Settings API.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does add_option() do if an option with that name already exists?

    add_option() never overwrites. Use update_option() to create-or-change a value.
  2. 2. Why is it a bad idea to autoload a 400 KB option?

    All autoloaded rows are fetched in one query at the start of every request, so a large value slows every page view.
  3. 3. get_transient() returns false. What can you conclude?

    false means a miss: it was never set, it expired, or it was evicted. Your code must rebuild the value.
  4. 4. update_option() returns false. Which statement is true?

    update_option() returns false when nothing changed, so do not treat false as an error without checking the value.

Summary

  • add_option(), get_option(), update_option() and delete_option() store named values in wp_options; prefix your names.
  • Arrays and objects are serialized automatically; keep option arrays small and never hand-edit serialized text.
  • Autoloaded options are loaded on every request, so autoload only small, widely used values.
  • *_site_option() functions work network-wide on multisite and fall back to normal options on a single site.
  • Transients are cache entries with an expiry; false means a miss, and they may disappear at any time.
  • With a persistent object cache, transients live in the cache instead of wp_options.

Next: The Settings API.