函数文档

get_transient()

💡 云策文档标注

概述

get_transient() 函数用于检索瞬态(transient)的值,适用于缓存数据。如果瞬态不存在、无值或已过期,则返回 false,开发者需注意使用恒等运算符(===)进行判断,并避免存储纯布尔值。

关键要点

  • 函数返回瞬态的值,若瞬态不存在、无值或已过期,则返回 false,应使用 === 进行严格比较。
  • 瞬态名称长度应不超过 172 字符,否则可能因 WordPress 在选项表中添加前缀而静默失败。
  • 返回值可能为 false,因此不建议用瞬态存储纯布尔值,可将其放入数组或转换为整数。
  • 函数支持过滤器钩子,如 pre_transient_{$transient} 可在检索前修改值,transient_{$transient} 可过滤现有瞬态的值。
  • 内部实现根据是否使用外部对象缓存或安装模式,通过 wp_cache_get() 或数据库选项处理。
  • 过期瞬态会在 get_transient() 调用时被删除,而非自动清理。

代码示例

// 获取瞬态数据,若不存在则生成并设置
if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    $special_query_results = new WP_Query( 'cat=5ℴ=random&tag;=tech&post;_meta_key=thumbnail' );
    set_transient( 'special_query_results', $special_query_results );
}
// 正常使用数据

注意事项

  • 启用对象缓存时,get_transient() 可能返回引用对象,导致数据意外修改,需注意对象克隆或序列化。
  • 开发阶段可结合 WP_DEBUG 条件语句,确保始终获取实时数据。

📄 原文内容

Retrieves the value of a transient.

Description

If the transient does not exist, does not have a value, or has expired, then the return value will be false.

Parameters

$transientstringrequired
Transient name. Expected to not be SQL-escaped.

Return

mixed Value of transient.

More Information

$transient parameter 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.

Returned value is the value of transient. If the transient does not exist, does not have a value, or has expired, then get_transient will return false. This should be checked using the identity operator ( === ) instead of the normal equality operator, because an integer value of zero (or other “empty” data) could be the data you’re wanting to store. Because of this “false” value, transients should not be used to hold plain boolean values. Put them into an array or convert them to integers instead.

Source

function get_transient( $transient ) {

	/**
	 * Filters the value of an existing transient before it is retrieved.
	 *
	 * The dynamic portion of the hook name, `$transient`, refers to the transient name.
	 *
	 * Returning a value other than false from the filter will short-circuit retrieval
	 * and return that value instead.
	 *
	 * @since 2.8.0
	 * @since 4.4.0 The `$transient` parameter was added
	 *
	 * @param mixed  $pre_transient The default value to return if the transient does not exist.
	 *                              Any value other than false will short-circuit the retrieval
	 *                              of the transient, and return that value.
	 * @param string $transient     Transient name.
	 */
	$pre = apply_filters( "pre_transient_{$transient}", false, $transient );

	if ( false !== $pre ) {
		return $pre;
	}

	if ( wp_using_ext_object_cache() || wp_installing() ) {
		$value = wp_cache_get( $transient, 'transient' );
	} else {
		$transient_option = '_transient_' . $transient;
		if ( ! wp_installing() ) {
			// If option is not in alloptions, it is not autoloaded and thus has a timeout.
			$alloptions = wp_load_alloptions();

			if ( ! isset( $alloptions[ $transient_option ] ) ) {
				$transient_timeout = '_transient_timeout_' . $transient;
				wp_prime_option_caches( array( $transient_option, $transient_timeout ) );
				$timeout = get_option( $transient_timeout );
				if ( false !== $timeout && $timeout < time() ) {
					delete_option( $transient_option );
					delete_option( $transient_timeout );
					$value = false;
				}
			}
		}

		if ( ! isset( $value ) ) {
			$value = get_option( $transient_option );
		}
	}

	/**
	 * Filters an existing transient's value.
	 *
	 * The dynamic portion of the hook name, `$transient`, refers to the transient name.
	 *
	 * @since 2.8.0
	 * @since 4.4.0 The `$transient` parameter was added
	 *
	 * @param mixed  $value     Value of transient.
	 * @param string $transient Transient name.
	 */
	return apply_filters( "transient_{$transient}", $value, $transient );
}

Hooks

apply_filters( “pre_transient_{$transient}”, mixed $pre_transient, string $transient )

Filters the value of an existing transient before it is retrieved.

apply_filters( “transient_{$transient}”, mixed $value, string $transient )

Filters an existing transient’s value.

Changelog

Version Description
2.8.0 Introduced.

User Contributed Notes

  1. Skip to note 5 content

    Example of using get_transient, set_transient and WP_Query

    // Get any existing copy of our transient data
    if ( false === ( $special_query_results = get_transient( 'special_query_results' ) ) ) {
    	// It wasn't there, so regenerate the data and save the transient
    	$special_query_results = new WP_Query( 'cat=5ℴ=random&tag;=tech&post;_meta_key=thumbnail' );
    	set_transient( 'special_query_results', $special_query_results );
    }
    
    // Use the data like you would have normally...

  2. Skip to note 6 content

    Useful to know: If the transient exists but has expired, the return value will not just be false. The expired transient will be deleted at the same time.

    WordPress does not delete expired transients on its own, but using get_transient() on an expired one will do so. Non-expired transients, or transients without expiration will only be deleted with delete_transient() .

  3. Skip to note 8 content

    Be careful: get_transient() might not return the same result whether an object cache is enabled or not.

    $obj = new stdClass();
    $obj->test = 'value';
    $obj->obj = new stdClass();
    $obj->obj->test = 'sub value';
    set_transient( 'test_sub_object', $obj );
    $obj->test = 'value modified';
    $obj->obj->test = 'sub value modified';
    $obj_from_transient = get_transient( 'test_sub_object' );

    Here $obj_from_transient->obj->test = 'sub value modified' not 'sub value' if an object cache is enabled (wp_get_cache is used in that case).