VOOZH about

URL: https://developer.wordpress.org/reference/functions/set_transient/

⇱ set_transient() – Function | Developer.WordPress.org


Skip to content

WordPress Developer Resources

set_transient()

HomeReferenceFunctionsset_transient()

set_transient( string $transient, mixed $value, int $expiration ): bool

Sets/updates the value of a transient.

Description

You do not need to serialize values. If the value needs to be serialized, then it will be serialized before it is set.

Parameters

$transientstringrequired
Transient name. Expected to not be SQL-escaped.
Must be 172 characters or fewer in length.
$valuemixedrequired
Transient value. Must be serializable if non-scalar.
Expected to not be SQL-escaped.
$expirationintoptional
Time until expiration in seconds. Default 0 (no expiration).

Return

bool True if the value was set, false otherwise.

More Information

For parameter $transient, if memcached is not enabled the name should be 172 characters or less in length as WordPress will prefix your name with “_transient_” or “_transient_timeout_” in the options table (depending on whether it expires or not). Longer key names will silently fail. See Trac #15058.

If a transient exists, this function will update the transient’s expiration time.

NB: transients that never expire are autoloaded, whereas transients with an expiration time are not autoloaded. Consider this when adding transients that may not be needed on every page, and thus do not need to be autoloaded, impacting page performance.

WordPress provides some constants for specifying time in seconds. Instead of multiplying out integers, see Transients_API#Using_Time_Constants.

Transient key names are limited to 191 characters due to the database schema in the wp_options table ( option_name: varchar(191) ).

In WordPress versions previous to 4.4, the length limitation was 45 in set_transient (now 172) and 64 in the database (now 191).

Source

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 '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;
}

View all references View on Trac View on GitHub

Hooks

apply_filters( “expiration_of_transient_{$transient}”, , ,  )

Filters the expiration for a transient before its value is set.

apply_filters( “pre_set_transient_{$transient}”, , ,  )

Filters a specific transient before its value is set.

do_action_deprecated( ‘setted_transient’, , ,  )

Fires after the transient is set.

do_action( ‘set_transient’, , ,  )

Fires after the value for a transient has been set.

do_action( “set_transient_{$transient}”, , ,  )

Fires after the value for a specific transient has been set.

Related

UsesDescription
wp_prime_option_caches()wp-includes/option.php

Primes specific options into the cache with a single database query.

do_action_deprecated()wp-includes/plugin.php

Fires functions attached to a deprecated action hook.

wp_installing()wp-includes/load.php

Checks or sets whether WordPress is in “installation” mode.

wp_cache_set()wp-includes/cache.php

Saves the data to the cache.

wp_using_ext_object_cache()wp-includes/load.php

Toggles $_wp_using_ext_object_cache on and off without directly touching global.

add_option()wp-includes/option.php

Adds a new option.

delete_option()wp-includes/option.php

Removes an option by name. Prevents removal of protected WordPress options.

apply_filters()wp-includes/plugin.php

Calls the callback functions that have been added to a filter hook.

do_action()wp-includes/plugin.php

Calls the callback functions that have been added to an action hook.

update_option()wp-includes/option.php

Updates the value of an option that was already added.

get_option()wp-includes/option.php

Retrieves an option value based on an option name.

Show 6 moreShow less
Used byDescription
WP_Automatic_Updater::has_fatal_error()wp-admin/includes/class-wp-automatic-updater.php

Performs a loopback request to check for potential fatal errors.

wp_add_global_styles_for_blocks()wp-includes/global-styles-and-settings.php

Adds global style rules to the inline style for each block.

clean_dirsize_cache()wp-includes/functions.php

Cleans directory size cache used by recurse_dirsize() .

WP_Site_Health::wp_cron_scheduled_check()wp-admin/includes/class-wp-site-health.php

Runs the scheduled event to check and update the latest site health status for the website.

wp_ajax_health_check_site_status_result()wp-admin/includes/ajax-actions.php

Handles site health check to update the result status via AJAX.

wp_edit_theme_plugin_file()wp-admin/includes/file.php

Attempts to edit a file for a theme or plugin.

WP_oEmbed_Controller::get_proxy_item()wp-includes/class-wp-oembed-controller.php

Callback for the proxy API endpoint.

install_themes_feature_list()wp-admin/includes/theme-install.php

Retrieves the list of WordPress theme features (aka theme tags).

wp_dashboard_cached_rss_widget()wp-admin/includes/dashboard.php

Checks to see if all of the feed url in $check_urls are cached.

wp_dashboard_plugins_output()wp-admin/includes/deprecated.php

Display plugins text for the WordPress news widget.

spawn_cron()wp-includes/cron.php

Sends a request to run cron through HTTP request that doesn’t halt page loading.

wp_rand()wp-includes/pluggable.php

Generates a random non-negative number.

wp_maybe_generate_attachment_metadata()wp-includes/media.php

Maybe attempts to generate attachment metadata, if missing.

recurse_dirsize()wp-includes/functions.php

Gets the size of a directory recursively.

is_multi_author()wp-includes/author-template.php

Determines whether this site has more than one author.

RSSCache::set()wp-includes/rss.php
Show 11 moreShow less

Changelog

VersionDescription
2.8.0Introduced.

User Contributed Notes

  1. Skip to note 7 content

    Unless you’re using an external object cache, when using set_transient() to update an existing transient that has an existing expiration, not providing an expiration value will maintain the existing expiration.

    For example:

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

    In this case, the expiration would remain as $initial + 300 (and not change to $update + 300, or never expires), because the second set_transient() call does not include an $expiration value (only the transient’s value is updated).

    Be careful though, because you may unintentionally set a transient to never expire, if the transient expired before the second call (without the $expiration parameter) is made.

  2. Skip to note 8 content

    This example shows how to set a transient with the latest five blog posts. It expires after one day.
    It uses time constants to set the expiration time.

    // Set the arguments for the custom query
    $args = array(
     'post_type' => 'post',
     'posts_per_page' => 5,
     'orderby' => 'date',
     'order' => 'DESC'
    );
    $latest_post = new WP_Query( $args );
    
    // Save the results in a transient named latest_5_posts
    set_transient( 'latest_5_posts', $latest_post, DAY_IN_SECONDS );

    To know more about how to get posts and custom post type items read the documentation of WP_Query.

  3. Skip to note 9 content

    Saving the $special_query_results object for 12 hours

    set_transient( 'special_query_results', $special_query_results, 12 * HOUR_IN_SECONDS );
  4. Skip to note 10 content

    WordPress saves the transients expiration time in the form of a UNIX timestamp. When you look for the

    _transient_timeout_{$transient}

    option name in the options table of WordPress, it will look like 1636453079 which is in UNIX timestamp not in seconds.
    See the code on GitHub

  5. Skip to note 11 content

    Beware! When you use a persistent object cache plugin, WordPress core stores transients in that persistent object cache, not in the wp_options table.

    Avoid the mistake of setting a transient by using the update_option API, or by writing something directly into the options table.

You must log in before being able to contribute a note or feedback.