Codex tools: Log in / create account
Contents |
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('WP_CACHE', true); to your wp-config.php file.
Tip: Make sure define('WP_CACHE', true); is above this block:
/* That's all, stop editing! Happy blogging. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'wp-settings.php');
Within a single page loading caching does still occur so as to reduce the number of database queries as much as possible
Almost all of these functions take a:
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.
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;