WordPress函数:get_transient 获取临时值

江河/ 2023年09月26日/ WordPress/ 浏览 508

函数原型:


get_transient( string $transient ): mixed


获取临时值。


如果临时值不存在,没有值或已过期,则返回false。


这应该使用标识运算符(==)而不是普通的相等运算符进行检查,因为整数值为零(或其他“空”数据)可能是您想要存储的数据。由于这个“假”值,瞬态不应用于保存纯布尔值。将它们放入数组中,或者将它们转换为整数。


函数源码:


function get_transient( $transient ) {
	$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;
				$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 );
		}
	}

	return apply_filters( "transient_{$transient}", $value, $transient );
}


包含钩子:


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

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


使用举例:


// 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&order=random&tag=tech&post_meta_key=thumbnail' );
	set_transient( 'special_query_results', $special_query_results );
}


发表评论

暂无评论,抢个沙发...

客服 工单