Transients and options are both ways to store a value in the WordPress database, but they work differently.
A transient is like an option that disappears after a set amount of time. They are used for temporary values, while options usually stick around.
tl;dr: Transients expire, options don’t. Use transients for a single value you only need temporarily, use options for persistent values that can change.
WordPress Transients
Transients expire, or disappear from the database, after a specific amount of time. They are generally a single value that is not changed.
Transient Example
Let’s say you show a popup to a new visitor. If the visitor dismisses the popup, you set a transient called ‘my_popup_dismissed’ that expires after 30 days. Then after 30 days the popup starts showing up again.
The set_transient function takes 3 arguments, name, value, and expiration (in seconds).
The code for that looks like this:
// when the user clicks dismiss, set the transient
if( $_POST['user_clicked_dismiss'] ) {
set_transient('my_popup_dismissed', true, 30 * DAY_IN_SECONDS );
}
When you display the popup, you would check for the transient like this:
if( FALSE !== get_transient('my_popup_dismissed') ) {
// show popup code here...
}
The get_transient function returns false if the value does not exist. If the value is false in our example above, that means the visitor has not dismissed the popup before, so we show it.
Caching
Transients are often used for caching, since they allow storing a chunk of data that can be retrieved quickly. For example, a post, and API response, or a wp_query result.
It was pointed out to me that transients can be stored outside the database, for example with an external object cache. This makes them much faster to retrieve.
There are probably a lot more subtleties to caching transients, but these are not things you need to worry about as a developer. Just know they can be a great way to serve content quickly.
WordPress Options
Options are values that are meant to stay in the database, and they can be changed or updated. For example, the admin email is a sitewide option that can be retrieved with get_option:
get_option('admin_email');
Options Example
You can also set custom options. Since options are meant to be updatable, we’ll use an example where the option is persistent, and it gets updated.
You can use update_option to save a new option, or update the value.
update_option( 'color_scheme', 'midnight' );
To change the option, you use the same function, and just change the value.
update_option( 'color_scheme', 'tropical' );
Options vs. Meta
You wouldn’t use options for something like allowing visitors to toggle a dark mode, languages, or time zones. Those are all personal to the site visitor, and should be stored in user meta instead.