2. What is Caching?
• Serve static content to the visitor without querying
the database.
• Not generated upon **every** request
• Reduce to API calls
3. Type of Caching?
• Page Cache - Whole page as static content
• Query Cache - Cache SQL query results
• Fragment Cache - Cache a piece of page
• Browser Cache - Cache page assets
• Opcode Cache - PHP executes faster
4. WordPress Caching APIs
Transients!
- Persistent out of the box
- Stored in wp_options
get_transient()
set_transient()
delete_transient()
Object Cache!
- Not persistent without a
persistent backend
- Storage depends on the
backend
wp_cache_add()
wp_cache_set()
wp_cache_get()
wp_cache_delete()
5. Using Transients
set_transient( $key, $value, $expiration );
<?php
// Get any existing copy of our transient data
$special_query = get_transient( 'special_query' );
if ( false === $special_query_results ) {
$special_query = new WP_Query( 'cat=5&order=random' );
set_transient( 'special_query', $special_query, 12 * HOUR_IN_SECONDS );
}
// Use the data like you would have normally...
Queries only after each 12 hours
6. Object Cache
• Not persistent. Means, valid for only one pageload
• Requires a persistent backend. Such as APC,
Memcached.
• Plugins like W3 Total Cache, Memcached Object
Cache helps.
• Used Extensively in WordPress
• Cache objects can be grouped
7. Object Cache Functions
// set the cache with value
wp_cache_add( $key, $data, $group, $expire )
wp_cache_set( $key, $data, $group, $expire )
// retrieve the value from cache
wp_cache_get( $key, $group )
// clears data from the cache for the given key.
wp_cache_replace( $key, $data, $group, $expire )
// clears all cached data.
wp_cache_flush()
8. Using Object Cache
$result = wp_cache_get( 'my_result' );
if ( false === $result ) {
$result = $wpdb->get_results( $query );
wp_cache_set( 'my_result', $result );
}
// Do something with $result;
http://codex.wordpress.org/Class_Reference/WP_Object_Cache
10. Fragment Caching
• Cache a fragment of a page
• This could be your menubar, widgets and other
query related parts.
https://gist.github.com/markjaquith/2653957