set_transient()WP 2.8.0

Sets or updates a transient option.

If the transient option being written already exists, the function will update the lifespan of the existing option and its value.

Transient options provide a standard and simple way to save data temporarily in the database (cache data). The data is saved in a specified option, which can be named anything and has a lifespan set, after which the option will be deleted. Transient options are identical to regular WordPress options. They differ only in that transient options have an added lifespan. This data is also saved in the wp_options table.

If an object caching plugin is installed on the site, transient options will be saved in the object cache, not in the wp_options table. See: wp_cache_set()

Auto-loading options. All options with the autoload flag in the wp_options table are requested in one query from the DB and saved in a PHP array (cache). See the $autoload parameter in add_option().

However, if the $expiration parameter is set for a transient option, it will not be automatically loaded into the global options array, and two simple queries will be made to the DB when retrieving it: one to get the option itself, and another to get the lifespan of the option. This note is valid if object caching is not installed on the site.

WordPress saves the expiration time of the transient option in a separate option with the name (key):

_transient_timeout_{$transient}

The value will store a number - a UNIX timestamp - which is the time when the option will be considered expired. For example, the number might look like 1636453079.

It is not necessary to serialize the value of the option being saved. If the value needs to be serialized, it will be done automatically before saving.

Deleting transient options. WP automatically deletes them after the expiration period. For this, the function delete_expired_transients() is run by cron.

Returns

true|false. true — the transient option was saved. false — the option was not saved.

Usage

set_transient( $transient, $value, $expiration );
$transient(string) (required)
The name of the transient option. Maximum length is 172 characters. Data with escaped slashes is expected; slashes are automatically cleaned before writing to the DB. The function automatically protects against SQL injections.
$value(mixed) (required)
The value of the transient option. Data with escaped slashes is expected; slashes are automatically cleaned before writing to the DB. The function protects against SQL injections. Serialization, if an array is passed, is also done automatically.
$expiration(string/array/number/object/boolean)

The lifespan of the option in seconds, starting from the current moment. For example, to set an option for one day, you need to specify 60 * 60 * 24.

If you specify 0 - the option will never be deleted and will have no expiration. This will make it a regular option, just with the prefix _transient_ in its name - this will mean that it is temporary and can be safely deleted during the cleanup of the wp_options table without the risk of breaking anything.

For convenience, WordPress has special time constants:

  • MINUTE_IN_SECONDS - 60 (seconds)
  • HOUR_IN_SECONDS - 60 * MINUTE_IN_SECONDS
  • DAY_IN_SECONDS - 24 * HOUR_IN_SECONDS
  • WEEK_IN_SECONDS - 7 * DAY_IN_SECONDS
  • YEAR_IN_SECONDS - 365 * DAY_IN_SECONDS

Default: 0

Examples

0

#1 Let's save the request

This example shows how to save the result of a complex SQL query to a transient option for 12 hours:

set_transient( 'special_query_results', $special_query_results, 12 * HOUR_IN_SECONDS );

Next, use get_transient() to get the result.

0

#2 Let's save the request for the last 5 posts to the transit option

This example shows how to get the last 5 posts and save the result for one day to a transient option.

// make a request
$latest_post = new WP_Query( array(
	'post_type'      => 'post',
	'posts_per_page' => 5,
	'orderby'        => 'date',
	'order'          => 'DESC'
) );

// Save the results to a transit option named latest_5_posts
set_transient( 'latest_5_posts', $latest_post, DAY_IN_SECONDS );

See WP_Query for more parameters to retrieve posts.

0

#3 The option lifetime can only be changed by specifying the third parameter and after expiration time is ended

Everything described below is true only if the external object cache is not used.

If you use the function to update an existing transient option that has not yet expired, the absence of the third parameter (expiration value) will keep the existing expiration time.

For example:

$initial = time();
set_transient( 'foo', 'bar', 300 );
sleep( 10 );
$update = time();
set_transient( 'foo', 'barbar' );

In this case the expiration time will remain as it was before $initial + 300 (and will not change to time() + 300, or will not be deleted), because if the $expiration parameter is not specified, the expiration time is not handled in any way and remains as it was.

Be careful, because you can unintentionally set the lifetime to never expires if it has expired and a second call is made without the $expiration parameter.

Changelog

Since 2.8.0 Introduced.

set_transient() code WP 6.8.1

function set_transient( $transient, $value, $expiration = 0 ) {

	$expiration = (int) $expiration;

	/**
	 * Filters a specific transient before its value is set.
	 *
	 * The dynamic portion of the hook name, `$transient`, refers to the transient name.
	 *
	 * @since 3.0.0
	 * @since 4.2.0 The `$expiration` parameter was added.
	 * @since 4.4.0 The `$transient` parameter was added.
	 *
	 * @param mixed  $value      New value of transient.
	 * @param int    $expiration Time until expiration in seconds.
	 * @param string $transient  Transient name.
	 */
	$value = apply_filters( "pre_set_transient_{$transient}", $value, $expiration, $transient );

	/**
	 * Filters the expiration for a transient before its value is set.
	 *
	 * The dynamic portion of the hook name, `$transient`, refers to the transient name.
	 *
	 * @since 4.4.0
	 *
	 * @param int    $expiration Time until expiration in seconds. Use 0 for no expiration.
	 * @param mixed  $value      New value of transient.
	 * @param string $transient  Transient name.
	 */
	$expiration = apply_filters( "expiration_of_transient_{$transient}", $expiration, $value, $transient );

	if ( wp_using_ext_object_cache() || wp_installing() ) {
		$result = wp_cache_set( $transient, $value, 'transient', $expiration );
	} else {
		$transient_timeout = '_transient_timeout_' . $transient;
		$transient_option  = '_transient_' . $transient;
		wp_prime_option_caches( array( $transient_option, $transient_timeout ) );

		if ( false === get_option( $transient_option ) ) {
			$autoload = true;
			if ( $expiration ) {
				$autoload = false;
				add_option( $transient_timeout, time() + $expiration, '', false );
			}
			$result = add_option( $transient_option, $value, '', $autoload );
		} else {
			/*
			 * If expiration is requested, but the transient has no timeout option,
			 * delete, then re-create transient rather than update.
			 */
			$update = true;

			if ( $expiration ) {
				if ( false === get_option( $transient_timeout ) ) {
					delete_option( $transient_option );
					add_option( $transient_timeout, time() + $expiration, '', false );
					$result = add_option( $transient_option, $value, '', false );
					$update = false;
				} else {
					update_option( $transient_timeout, time() + $expiration );
				}
			}

			if ( $update ) {
				$result = update_option( $transient_option, $value );
			}
		}
	}

	if ( $result ) {

		/**
		 * Fires after the value for a specific transient has been set.
		 *
		 * The dynamic portion of the hook name, `$transient`, refers to the transient name.
		 *
		 * @since 3.0.0
		 * @since 3.6.0 The `$value` and `$expiration` parameters were added.
		 * @since 4.4.0 The `$transient` parameter was added.
		 *
		 * @param mixed  $value      Transient value.
		 * @param int    $expiration Time until expiration in seconds.
		 * @param string $transient  The name of the transient.
		 */
		do_action( "set_transient_{$transient}", $value, $expiration, $transient );

		/**
		 * Fires after the value for a transient has been set.
		 *
		 * @since 6.8.0
		 *
		 * @param string $transient  The name of the transient.
		 * @param mixed  $value      Transient value.
		 * @param int    $expiration Time until expiration in seconds.
		 */
		do_action( 'set_transient', $transient, $value, $expiration );

		/**
		 * Fires after the transient is set.
		 *
		 * @since 3.0.0
		 * @since 3.6.0 The `$value` and `$expiration` parameters were added.
		 * @deprecated 6.8.0 Use {@see 'set_transient'} instead.
		 *
		 * @param string $transient  The name of the transient.
		 * @param mixed  $value      Transient value.
		 * @param int    $expiration Time until expiration in seconds.
		 */
		do_action_deprecated( 'setted_transient', array( $transient, $value, $expiration ), '6.8.0', 'set_transient' );
	}

	return $result;
}