speed things up with transients
@cliffseal#wptrans
logos-creative.com/     wcatl
LOL WUTAPI?is the Transients
The Transients API“offers a simple and standardizedway of storing cached data in thedatabase temporarily by giving it acus...
The Transients API✓ like Options API, but with expiration✓ uses fast memory (if configured)✓ uses database otherwise
Native        Object Cache Plugin               Persistent Option                              N/A              (database)...
thetransientsAPI         Tweets             Friends                Scrobbles                  Options API: Username, URL, ...
thetransientsAPI         Tag Cloud   Ratings   Custom Queries      expensivequeries
3mainfunctions
mainfunctions        set_transient(           $transient,           $value,           $expiration        );         set_tr...
mainfunctions$transient✓   (string) a unique identifier for your cached data✓   45 characters or less in length✓   For sit...
mainfunctions$value✓   (array|object) Data to save, either a regular variable or an    array/object✓   Handles serializati...
mainfunctions$expiration✓   (integer) number of seconds to keep the data before    refreshing✓   Example: 60*60*24 or 8640...
mainfunctionsMINUTE_IN_SECONDS   =   60 (seconds)HOUR_IN_SECONDS     =   60 * MINUTE_IN_SECONDSDAY_IN_SECONDS      =   24 ...
mainfunctionsget_transient($transient);✓   If the transient does not exist, or has expired, returns false✓   An integer va...
mainfunctionsdelete_transient($transient);      delete_transient
mainfunctions set_site_transient(); get_site_transient();delete_site_transient();                These work ‘network wide’...
3exampleusecases
cachetagcloud
cachetagcloudfunction get_tag_cloud() {    if ( false === ( $tag_cloud = get_transient( my_tag_cloud ) ) ) {        $tag_c...
EXPERTMODE
cachetagcloudfunction edit_term_delete_tag_cloud() {    delete_transient( my_tag_cloud );}add_action( edit_post, edit_term...
cachemyissues
cachemyissuesfunction we_have_issues() {    if ( false === ( $issues = get_transient( we_have_issues ) ) ) {        $respo...
EXPERTMODE
cachemyissuesfunction refresh_my_issues() {    delete_transient( we_have_issues );}if ( is_admin() && isset($_GET[forcedel...
cachebigquery
cachebigqueryfunction query_for_commenters() {    if ( false === ( $commenters = get_transient( top_commenters_cached ) ) ...
cachebigqueryfunction delete_query_for_commenters() {    delete_transient( top_commenters_cached );}add_action( comment_po...
cachebigqueryfunction popular_posts( $num=10 ) {    if ( false === ( $popular = get_transient( popular_posts . $num ) ) ){...
cachebigquery$newquery = popular_posts(3);if ( $newquery->have_posts() ) {    while ( $newquery->have_posts() ) {        $...
cachebigqueryfunction clear_popular_posts() {    for ( $i = 0; $i < 50; $i++ ) {        delete_transient( popular_posts . ...
EXPERTMODE
cachebigquery    Once a transient expires, it remains so until the new result is saved.    Heavy traffic can mean too many...
cachebigquery$newquery = popular_posts_panic(3);if ( $newquery !==  ) {    if ( $newquery->have_posts() ) {        while (...
cachebigqueryfunction renew_popular_posts() {    for ( $i = 0; $i < 50; $i++ ) {        if ( false === ( $popular = get_tr...
TOP OF HACKER NEWS  CONQUERED
4warnings
expiry&garbagecollection✓ everything works on request✓ expired != deleted, unless requested✓ unrequested, undeleted transi...
scalarvalues✓ accepts scalar values (integer, float,  string or boolean) & non-scalar  serializable values (arrays, some  ...
infinitetransients✓ transients set without an expiration  time are autoloaded✓ if you don’t need it on every page, set  an...
cachinggotchas✓ in some shared hosting environments,  object caching can be slower than  using the database; check your ho...
3usefultools
usefultools    TLC Transients                               Artiss Transient Cleaner                       Debug Bar Trans...
?questions
logos-creative.com/     wcatl
Speed Things Up with Transients
Upcoming SlideShare
Loading in...5
×

Speed Things Up with Transients

785
-1

Published on

Especially when looking at WordPress as a potential platform for web apps, understanding proper caching techniques is a must—and the Transients API is a powerful tool that sometimes goes unnoticed.

We’ll cover the basics and see easy examples, and then discuss common places where this method can be most helpful, like large, complex queries or pulling from an external API. We’ll also get into the details of the API, covering concepts like object caching, autoloading, and see some examples of more advanced setups.

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
785
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
4
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Speed Things Up with Transients

  1. 1. speed things up with transients
  2. 2. @cliffseal#wptrans
  3. 3. logos-creative.com/ wcatl
  4. 4. LOL WUTAPI?is the Transients
  5. 5. The Transients API“offers a simple and standardizedway of storing cached data in thedatabase temporarily by giving it acustom name and a timeframe afterwhich it will expire and be deleted.”
  6. 6. The Transients API✓ like Options API, but with expiration✓ uses fast memory (if configured)✓ uses database otherwise
  7. 7. Native Object Cache Plugin Persistent Option N/A (database) PersistentTransient Persistent (varies) (database) Non-persistent Cache Persistent (varies) (memory) Thanks to Rarst.
  8. 8. thetransientsAPI Tweets Friends Scrobbles Options API: Username, URL, ID externalAPIs
  9. 9. thetransientsAPI Tag Cloud Ratings Custom Queries expensivequeries
  10. 10. 3mainfunctions
  11. 11. mainfunctions set_transient( $transient, $value, $expiration ); set_transient
  12. 12. mainfunctions$transient✓ (string) a unique identifier for your cached data✓ 45 characters or less in length✓ For site transients, 40 characters or less in length set_transientargs
  13. 13. mainfunctions$value✓ (array|object) Data to save, either a regular variable or an array/object✓ Handles serialization of complex data for you set_transientargs
  14. 14. mainfunctions$expiration✓ (integer) number of seconds to keep the data before refreshing✓ Example: 60*60*24 or 86400 (24 hours) set_transientargs
  15. 15. mainfunctionsMINUTE_IN_SECONDS = 60 (seconds)HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDSDAY_IN_SECONDS = 24 * HOUR_IN_SECONDSWEEK_IN_SECONDS = 7 * DAY_IN_SECONDSYEAR_IN_SECONDS = 365 * DAY_IN_SECONDS timeconstants
  16. 16. mainfunctionsget_transient($transient);✓ If the transient does not exist, or has expired, returns false✓ An integer value of zero/empty could be the stored data✓ Should not be used to hold plain boolean values; array or integers instead get_transient
  17. 17. mainfunctionsdelete_transient($transient); delete_transient
  18. 18. mainfunctions set_site_transient(); get_site_transient();delete_site_transient(); These work ‘network wide’. wpmultisite
  19. 19. 3exampleusecases
  20. 20. cachetagcloud
  21. 21. cachetagcloudfunction get_tag_cloud() { if ( false === ( $tag_cloud = get_transient( my_tag_cloud ) ) ) { $tag_cloud = wp_tag_cloud( echo=0 ); set_transient( my_tag_cloud, $tag_cloud, 60*60*24 ); } else { $tag_cloud = get_transient( my_tag_cloud ); } return $tag_cloud;}
  22. 22. EXPERTMODE
  23. 23. cachetagcloudfunction edit_term_delete_tag_cloud() { delete_transient( my_tag_cloud );}add_action( edit_post, edit_term_delete_tag_cloud );
  24. 24. cachemyissues
  25. 25. cachemyissuesfunction we_have_issues() { if ( false === ( $issues = get_transient( we_have_issues ) ) ) { $response = wp_remote_get(https://api.github.com/repos/twitter/bootstrap/issues?assignee); if ( is_wp_error( $response ) ) { $error_message = $response->get_error_message(); echo "This borked: " . $error_message; } else { $issues = wp_remote_retrieve_body($response); set_transient( we_have_issues, $issues, 60*60*24 ); } } else { $issues = get_transient( we_have_issues ); } $issues = json_decode($issues, true); $issuereturn = ; for ( $i = 0; $i < 5; $i++ ) { $issuereturn .= "<h3><a href=" . $issues[$i]["html_url"] . ">".$issues[$i]["title"] . "</a></h3>"; } return $issuereturn;}
  26. 26. EXPERTMODE
  27. 27. cachemyissuesfunction refresh_my_issues() { delete_transient( we_have_issues );}if ( is_admin() && isset($_GET[forcedel]) && $_GET[forcedel] === yes ) { refresh_my_issues();}function refresh_via_admin_bar() { global $wp_admin_bar; $wp_admin_bar->add_menu( array( title => __(Refresh), href => admin_url(?forcedel=yes), id => refresh-issues, parent => false ) );}add_action( wp_before_admin_bar_render, refresh_via_admin_bar );
  28. 28. cachebigquery
  29. 29. cachebigqueryfunction query_for_commenters() { if ( false === ( $commenters = get_transient( top_commenters_cached ) ) ) { global $wpdb; $commenters = $wpdb->get_results(" select count(comment_author) as comments_count, comment_author, comment_type ! ! ! from $wpdb->comments ! ! ! where comment_type != pingback ! ! ! and comment_author != ! ! ! and comment_approved = 1 ! ! ! group by comment_author ! ! ! order by comment_author desc ! ! ! LIMIT 10 "); set_transient( top_commenters_cached, $commenters, 60*60*24 ); } else { $commenters = get_transient( top_commenters_cached ); } $comment_list = <ol>; foreach($commenters as $commenter) { $comment_list .= <li>; $comment_list .= $commenter->comment_author; $comment_list .= ( . $commenter->comments_count . ); $comment_list .= </li>; } $comment_list .= </ol>; return $comment_list;}
  30. 30. cachebigqueryfunction delete_query_for_commenters() { delete_transient( top_commenters_cached );}add_action( comment_post, delete_query_for_commenters );
  31. 31. cachebigqueryfunction popular_posts( $num=10 ) { if ( false === ( $popular = get_transient( popular_posts . $num ) ) ){ $query = new WP_Query( array( orderby => comment_count, posts_per_page => $num ) ); set_transient( popular_posts . $num, $query, 60*60*24 ); } else { $query = get_transient( popular_posts . $num ); } return $query;}
  32. 32. cachebigquery$newquery = popular_posts(3);if ( $newquery->have_posts() ) { while ( $newquery->have_posts() ) { $newquery->the_post(); ?> <h4><?php the_title(); ?></h4> <?php the_excerpt(); ?> <?php } wp_reset_postdata();}
  33. 33. cachebigqueryfunction clear_popular_posts() { for ( $i = 0; $i < 50; $i++ ) { delete_transient( popular_posts . $i ); }}add_action( edit_post, clear_popular_posts );
  34. 34. EXPERTMODE
  35. 35. cachebigquery Once a transient expires, it remains so until the new result is saved. Heavy traffic can mean too many concurrent MySQL connections.function popular_posts_panic( $num=10 ) { if ( false === ( $popular =get_transient( popular_posts . $num ) ) ) { return ; } else { $query = get_transient( popular_posts . $num ); } return $query;} Thanks to Andrew Gray for the idea.
  36. 36. cachebigquery$newquery = popular_posts_panic(3);if ( $newquery !== ) { if ( $newquery->have_posts() ) { while ( $newquery->have_posts() ) { $newquery->the_post(); ?> <h4><?php the_title(); ?></h4> <?php the_excerpt(); ?> <?php } wp_reset_postdata(); }}
  37. 37. cachebigqueryfunction renew_popular_posts() { for ( $i = 0; $i < 50; $i++ ) { if ( false === ( $popular = get_transient( popular_posts .$i ) ) ) { delete_transient( popular_posts . $i ); $query = new WP_Query( array( orderby => comment_count, posts_per_page => $i ) ); set_transient( popular_posts . $i, $query, 60*60*24*365 ); } }}if ( !wp_next_scheduled( renew_popular_posts ) ) { wp_schedule_event( time(), hourly, renew_popular_posts );}
  38. 38. TOP OF HACKER NEWS CONQUERED
  39. 39. 4warnings
  40. 40. expiry&garbagecollection✓ everything works on request✓ expired != deleted, unless requested✓ unrequested, undeleted transients stay until you remove them explicitly
  41. 41. scalarvalues✓ accepts scalar values (integer, float, string or boolean) & non-scalar serializable values (arrays, some objects)✓ SimpleXMLElement will FREAK. OUT., so convert it to a string or array of objects (i.e. simplexml_load_string)
  42. 42. infinitetransients✓ transients set without an expiration time are autoloaded✓ if you don’t need it on every page, set an expiration (even if it’s a year)✓ consider the Options API for non- transient data
  43. 43. cachinggotchas✓ in some shared hosting environments, object caching can be slower than using the database; check your host’s recommended settings✓ always use the Transients API to access transients; don’t assume they’re in the database (or vice versa)
  44. 44. 3usefultools
  45. 45. usefultools TLC Transients Artiss Transient Cleaner Debug Bar Transients Supports soft- Deletes expired Adds panel to Debug expiration, transients and optimizes Bar with transient info background updating table
  46. 46. ?questions
  47. 47. logos-creative.com/ wcatl
  1. A particular slide catching your eye?

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

×