Upload
lime-canvas
View
53
Download
1
Embed Size (px)
DESCRIPTION
Reduce WordPress web page load speed by using transients as caching
Citation preview
www.limecanvas.com
Most WordPress content is stored in the DB
WordPress has a great DB API to get content
However…
Too many DB calls = slow page response
Solution: Reduce the number of DB calls
You want to display the latest 10 posts (title & excerpt) on a web page where editors post new articles every 6 hours.
Easy solution:
Use a custom WPQuery to retrieve all the data.
Output data directly to the web page.
Same WPQuery is called every time the web page is accessed.
And outputting the same results every time (assuming no new posts for next 6 hours)
Poor DB Poor Server Annoyed User
WP transients are a caching system.
Used to store any data that will expire in the future.
1. They are first stored in the DB.
2. Then they stored in WP internal object cache.
= data is retrieved from memory, not the DB
get_transient( $name ) Note: Returns FALSE if no transient exists
set_transient( $name, $value, $expiration ) Note: $expiration is in seconds
delete_transient( $name )
global $wpdb;
$transient_name = 'lc-latest-10-posts';
$post_info = get_transient( $transient_name );
if ( $post_info == FALSE ){
$sql = "SELECT post.post_title, post.post_excerpt
FROM $wpdb->posts post
WHERE post.post_type = 'post'
AND post.post_status = 'publish'
ORDER BY post.post_date DESC
LIMIT 0,10";
$results = $wpdb->get_results( $sql, OBJECT );
if( $results ){
foreach ( $results as $result ){
$post_info[] = array(
‘title’ => $result->post_title, ‘excerpt’ => $result->post_excerpt );
}
set_transient( $transient_name, $post_info, 60 * 60 * 6 );
}
}
Does the transient exist? get_transient()
Yes? Do nothing – we have the data
No? Do the query and get the results latest 10 posts
Spin through results & store Post Title & Excerpt in an array
Create the transient, expiry = 6hrs set_transient()
Transient stored – we have the data - job done!
Now run through the steps above once more.
get_site_transient( $name )
set_site_transient( $name, $value, $expiry )
delete_site_transient( $name )
All take the same parameters as the regular functions.
Transient expiration does not mean deletion.
Expired transients are only deleted when they are accessed after expiration date.
Potentially many expired transients in DB.
Get a transient cleaner plugin.
eCommerce sites can generate many expired transients.
[1] media.dma.mil
[7] memegenerator.net