0
An Introduction toAdvanced Caching   methods in WordPress
Maor ChasenWP Developer @ illumineaCore contributor for 3.5Have plugins on WordPress.orgOpen Source FanaticDesign Enthusia...
Its not scary.Its fun.
Why caching is good for you?A question you shouldnt ask your mom 1. Its easy 2. Your site = faster 3. Can save you $$ 4. I...
What we will talk about● What is fragment / object caching● Why caching is important● How to cache● What to cache● When to...
What we wont talk about● Server setups● Caching plugins
first things firstTransients API
Transients are●   temporary bits of data (usually raw data)●   like options, but w/ expiration time●   always persistent o...
Use Transients when●   fetching data from a remote source●   performing an expensive* query or request    ○   meta_query  ...
Transients functionsat your disposalread core?wp-includes/option.php
Get it.get_transient( $transient );     unique string (key) representing a piece of data
Set it.set_transient(  $transient,  $value,         the data you wish to store  $expiration = 0             for how long?);
Scrap it.delete_transient( $transient );     unique string (key) representing a piece of data
Multisite?Youre in luck! All Transients functionshave their network-wide counterparts.get_site_transient();set_site_transi...
Use case:Using Transients to storefragmented data
wp_nav_menu( array(   theme_location => primary,) );<ul id="menu-primary" class="menu">        <li id="menu-item-10" class...
Without usingwp_nav_menu()After usingwp_nav_menu()     That is ~5 extra queries                (for each menu)
Instead, we can cache themenu in a transientand save on DB queries
// Get an existing copy of our transient data$menu_html = get_transient( wcj_2013_menu );if ( false === $menu_html ) {    ...
// Get an existing copy of our transient data$menu_html = get_transient( wcj_2013_menu );if ( false === $menu_html ) {    ...
Now, lets invalidatefunction wcj_2013_invldt_menu( $menu_id, $menu_data ) {        delete_transient( wcj_2013_menu );}add_...
Use Transients when fetchingdata from a remote sourcehttp://...https://...
Pick your poison Twitter APIFacebook API    last.fm API       Google+ API
Example (Twitter API):Retrieve follower countand cache the results
function wcj_2013_get_twitter_followers_for( $handle ) {        $key = "wcj_2013_followers_$handle";        if ( false ===...
function wcj_2013_get_twitter_followers_for( $handle ) {        $key = "wcj_2013_followers_$handle";        if ( false ===...
function wcj_2013_get_twitter_followers_for( $handle ) {        $key = "wcj_2013_followers_$handle";        if ( false ===...
function wcj_2013_get_twitter_followers_for( $handle ) {        $key = "wcj_2013_followers_$handle";        if ( false ===...
Lets spice it upGot some metrics!
Without Transients0.36014295 secondsWITH Transients0.00010109 seconds
That is3,562 X FASTER
last but not leastObject Cache API
Object Cache is●   non-persistent out of the box●   stored in PHP memory by default●   ideally* persistent when a caching ...
Common use of the Object Cache API                                          DB        Is post_id            = 13          ...
Object Cache functionsat your disposalread core?wp-includes/cache.php
Object Cache functionsat your disposal●   wp_cache_add( $k, $d, $g, $ex )●   wp_cache_get( $k )●   wp_cache_set( $k, $d, $...
Example$song_obj = wp_cache_get( $id, songs );if ( false === $song_obj ) {        $song_obj = $wpdb->get_row(             ...
Best Practicesfor the best of us● prefer refreshing the cache ONLY when data is   added/changed● Avoid, if possible, cachi...
Side-by-side comparison                                                        Memory Cache                               ...
Thanks!Questions?@maorhkeep in touch
Intro to advanced caching in WordPress
Intro to advanced caching in WordPress
Intro to advanced caching in WordPress
Upcoming SlideShare
Loading in...5
×

Intro to advanced caching in WordPress

1,197

Published on

Presented at WordCamp Jerusalem 2013 (Feb. 20, 2013)

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,197
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
7
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Intro to advanced caching in WordPress"

  1. 1. An Introduction toAdvanced Caching methods in WordPress
  2. 2. Maor ChasenWP Developer @ illumineaCore contributor for 3.5Have plugins on WordPress.orgOpen Source FanaticDesign EnthusiastFlying kites
  3. 3. Its not scary.Its fun.
  4. 4. Why caching is good for you?A question you shouldnt ask your mom 1. Its easy 2. Your site = faster 3. Can save you $$ 4. It will knock your socks off 5. Youll sleep better at night.
  5. 5. What we will talk about● What is fragment / object caching● Why caching is important● How to cache● What to cache● When to cache
  6. 6. What we wont talk about● Server setups● Caching plugins
  7. 7. first things firstTransients API
  8. 8. Transients are● temporary bits of data (usually raw data)● like options, but w/ expiration time● always persistent out of the box● stored in wp_options by default● stored in memory if a caching backend (APC, Memcache, XCache, etc.) is available● available since 2.8
  9. 9. Use Transients when● fetching data from a remote source● performing an expensive* query or request ○ meta_query ○ tax_query● data persistence is absolutely required*** operations that require high CPU usage or high latency (Identify slowqueries with Debug Bar)** ex. - when polling data from external sources
  10. 10. Transients functionsat your disposalread core?wp-includes/option.php
  11. 11. Get it.get_transient( $transient ); unique string (key) representing a piece of data
  12. 12. Set it.set_transient( $transient, $value, the data you wish to store $expiration = 0 for how long?);
  13. 13. Scrap it.delete_transient( $transient ); unique string (key) representing a piece of data
  14. 14. Multisite?Youre in luck! All Transients functionshave their network-wide counterparts.get_site_transient();set_site_transient();delete_site_transient();
  15. 15. Use case:Using Transients to storefragmented data
  16. 16. wp_nav_menu( array( theme_location => primary,) );<ul id="menu-primary" class="menu"> <li id="menu-item-10" class="menu-item"> <a href="...">...</a> </li> ...</ul>
  17. 17. Without usingwp_nav_menu()After usingwp_nav_menu() That is ~5 extra queries (for each menu)
  18. 18. Instead, we can cache themenu in a transientand save on DB queries
  19. 19. // Get an existing copy of our transient data$menu_html = get_transient( wcj_2013_menu );if ( false === $menu_html ) { // data is not available, lets generate it $menu_html = wp_nav_menu( array( theme_location => primary, returns the echo => false, menu instead ) ); of printing set_transient( wcj_2013_menu, $menu_html, DAY_IN_SECONDS );}// do something with $menu_htmlecho $menu_html; 60 * 60 * 24
  20. 20. // Get an existing copy of our transient data$menu_html = get_transient( wcj_2013_menu );if ( false === $menu_html ) { // data is not available, lets generate it $menu_html = wp_nav_menu( array( theme_location => primary, echo => false, ) ); set_transient( wcj_2013_menu, $menu_html );}// do something with $menu_htmlecho $menu_html; doesnt expire, but it might anyway
  21. 21. Now, lets invalidatefunction wcj_2013_invldt_menu( $menu_id, $menu_data ) { delete_transient( wcj_2013_menu );}add_action( wp_update_nav_menu, wcj_2013_invldt_menu, 10, 2 ); this action runs whenever a menu is being saved
  22. 22. Use Transients when fetchingdata from a remote sourcehttp://...https://...
  23. 23. Pick your poison Twitter APIFacebook API last.fm API Google+ API
  24. 24. Example (Twitter API):Retrieve follower countand cache the results
  25. 25. function wcj_2013_get_twitter_followers_for( $handle ) { $key = "wcj_2013_followers_$handle"; if ( false === ( $followers_count = get_transient( $key ) ) ) { // transient expired, regenerate! $followers_count = wp_remote_retrieve_body( wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name=$handle" ) ); // request failed? if ( empty( $followers_count ) ) return false; // extract the number of followers $json = (object) json_decode( $followers_count ); $followers_count = absint( $json->followers_count ); // request was complete, store data in a transient for 6 hours set_transient( $key, $followers_count, 6 * HOUR_IN_SECONDS ); } return $followers_count;}
  26. 26. function wcj_2013_get_twitter_followers_for( $handle ) { $key = "wcj_2013_followers_$handle"; if ( false === ( $followers_count = get_transient( $key ) ) ) { // transient expired, regenerate! $followers_count = wp_remote_retrieve_body( wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name=$handle" ) ); // request failed? if ( empty( $followers_count ) ) return false; // extract the number of followers $json = (object) json_decode( $followers_count ); $followers_count = absint( $json->followers_count ); // request was complete, store data in a transient for 6 hours set_transient( $key, $followers_count, 6 * HOUR_IN_SECONDS ); } return $followers_count;}
  27. 27. function wcj_2013_get_twitter_followers_for( $handle ) { $key = "wcj_2013_followers_$handle"; if ( false === ( $followers_count = get_transient( $key ) ) ) { // transient expired, regenerate! $followers_count = wp_remote_retrieve_body( wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name=$handle" ) ); // request failed? if ( empty( $followers_count ) ) return false; // extract the number of followers $json = (object) json_decode( $followers_count ); $followers_count = absint( $json->followers_count ); // request was complete, store data in a transient for 6 hours set_transient( $key, $followers_count, 6 * HOUR_IN_SECONDS ); } return $followers_count;}
  28. 28. function wcj_2013_get_twitter_followers_for( $handle ) { $key = "wcj_2013_followers_$handle"; if ( false === ( $followers_count = get_transient( $key ) ) ) { // transient expired, regenerate! $followers_count = wp_remote_retrieve_body( wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name=$handle" ) ); // request failed? if ( empty( $followers_count ) ) return false; // extract the number of followers $json = (object) json_decode( $followers_count ); $followers_count = absint( $json->followers_count ); // request was complete, store data in a transient for 6 hours set_transient( $key, $followers_count, 6 * HOUR_IN_SECONDS ); } return $followers_count;}printf( I have %d followers!, wcj_2013_get_twitter_followers_for( maorh ) );
  29. 29. Lets spice it upGot some metrics!
  30. 30. Without Transients0.36014295 secondsWITH Transients0.00010109 seconds
  31. 31. That is3,562 X FASTER
  32. 32. last but not leastObject Cache API
  33. 33. Object Cache is● non-persistent out of the box● stored in PHP memory by default● ideally* persistent when a caching backend is available● similar to Transients● available since 2.0* Success depends on server environment
  34. 34. Common use of the Object Cache API DB Is post_id = 13 No SELECT * cached? FROM wp_posts WHERE ID = 13 Yes Do something with that Store results in Object post Cache
  35. 35. Object Cache functionsat your disposalread core?wp-includes/cache.php
  36. 36. Object Cache functionsat your disposal● wp_cache_add( $k, $d, $g, $ex )● wp_cache_get( $k )● wp_cache_set( $k, $d, $g, $ex )● wp_cache_delete( $k, $g )● wp_cache_incr( $k, $offset, $g )$key, $data, $group, $expiration
  37. 37. Example$song_obj = wp_cache_get( $id, songs );if ( false === $song_obj ) { $song_obj = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM$wpdb->songs WHERE ID = %d", $id ) ); wp_cache_set( $id, $song_obj, songs );}// do something with $song_obj
  38. 38. Best Practicesfor the best of us● prefer refreshing the cache ONLY when data is added/changed● Avoid, if possible, caching on front end page requests (instead, generate the data on an admin event*)● Design to fail gracefully (never assume that data is in the cache)* useful events: publish_post, transition_post_status, created_{$taxonomy}, edited_{$taxonomy}
  39. 39. Side-by-side comparison Memory Cache Out of the box Backend Transients API persistent - database Persistent non-persistent - Object Cache API Ideally Persistent memoryhttp://wordpress.stackexchange.com/a/45137
  40. 40. Thanks!Questions?@maorhkeep in touch
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×