wp_cache_get_last_changed()WP 4.7.0

Gets the timestamp of the last modification of the specified object cache group.

The obtained timestamp shows when the specified object cache group was last modified.

This function can be useful, for example, when data is being collected in the cache group foo, and whenever the data of this group changes, the cache of any element of the group needs to be considered expired. For this, you can take the value of this function (the time of data modification) and add it to the cache key. Thus, with any change in time, the cache key will change, and therefore the data under the specified key in the cache will no longer exist.

All of this is obviously necessary because in WP there is no way to delete data of a specific cache group (i.e., you cannot delete the cache of the entire group, you can only delete the cache by a specific key or the entire cache).

This function works with the object cache itself, i.e., it takes the data changes from there. This means that for it to work correctly, after adding data to the group, the timestamp of the data modification must also be updated.

For example, if we are working with the cache group posts, then after adding data to the cache of this group, the data modification timestamp should be updated like this:

wp_cache_set( 'last_changed', microtime(), 'posts' );
// microtime() = 0.77065000 1560530885

Only after such an update will this function return the current timestamp:

echo wp_cache_get_last_changed( 'posts' ); // 0.77065000 1560530885

No Hooks.

Returns

String. UNIX timestamp (with microseconds).

Usage

wp_cache_get_last_changed( $group );
$group(string) (required)
The name of the object cache group.
The group is specified in the third parameter of the function wp_cache_set().

Examples

0

#1 Example of using time tags when creating a cache

A stripped down piece of code from the kernel, which is used in the get_pages() function to cache its results.

function some_cache_orientated_function(){

	$key = md5( serialize( 'Some data, whatever' ) );

	$last_changed = wp_cache_get_last_changed( 'posts' );

	$cache_key = "get_pages:$key:$last_changed";

	// get the cache
	$cache = wp_cache_get( $cache_key, 'posts' );

	// there is a cache, let's bring it back
	if ( false !== $cache ) {
		return $pages;
	}

	$pages = $wpdb->get_results('SQL query for posts' );

	// keep only the ID
	$page_structure = array();
	foreach ( $pages as $page ) {
		$page_structure[] = $page->ID;
	}

	// no cache, get the data and save it in the cache
	wp_cache_set( $cache_key, $page_structure, 'posts' );

	return $pages;
}

Changelog

Since 4.7.0 Introduced.

wp_cache_get_last_changed() code WP 6.8.3

function wp_cache_get_last_changed( $group ) {
	$last_changed = wp_cache_get( 'last_changed', $group );

	if ( $last_changed ) {
		return $last_changed;
	}

	return wp_cache_set_last_changed( $group );
}