WordPress 中文文档
Function Reference/WP Cache
From WordPress Chinese
目录 |
Role of WP_Cache
WP_Object_Cache is WordPress' class for caching data which may be computationally intensive to regenerate dynamically on every page load. It's defined in wp-includes/cache.php.
Do not use the class directly in your code when writing plugins, but use the wp_cache functions listed here.
Caching to file to store the information across page loads is not enabled by default - this can be enabled by adding define('ENABLE_CACHE', true); to your wp-config.php file.
Within a single page loading caching does still occur so as to reduce the number of database queries as much as possible
wp_cache functions
Almost all of these functions take a:
- key: the key to indicate the value
- $data: the value you want to store
- flag: optional: this is a way of grouping your cache data. If you use a flag, your data will be stored in a subdirectory of your cache directory
- expire: number of seconds (by default 900)
wp_cache_add($key, $data, $flag = '', $expire = 0)
This function first checks if there is a cached object on the given $key. If not, then it is saved, otherwise returns false.
wp_cache_delete($id, $flag = '')
Clears a given file.
wp_cache_get($id, $flag = '')
Gives back the value of the cached object if it did not expired. Otherwise gives back false.
wp_cache_replace($key, $data, $flag = '', $expire = 0)
Replaces the given cache if it exists, returns false otherwise.
wp_cache_set($key, $data, $flag = '', $expire = 0)
Sets the value of the cache object. If the object already exists, then it will be overwritten, if the object does not exists it will be created.
wp_cache_init()
Initializes a new cache object. This function is called by Wordpress at initialization if cacheing is enabled.
wp_cache_flush()
Clears all the cache files.
wp_cache_close()
Saves the cached object. This function is called by Wordpress at the shutdown action hook.
Examples
You can use WP_Object_Cache and Snoopy to cache offsite includes:
$news = wp_cache_get('news');
if($news == false) {
$snoopy = new Snoopy;
$snoopy->fetch('http://example.com/news/');
$news = $snoopy->results;
wp_cache_set('news', $news);
}
echo $news;
Additional Resources
- Dougal Campbell wrote a short guide on how to use the Wordpress Cache object from within your own plugins : Using the Wordpress Object Cache
- Peter Westwood has a plugin to help people analyse the behaviour of the cache, provides the administrator with a quick overview of how the cache is performming and what queries are cached : WP Cache Inspect
