SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
speed things up with
 transients
@cliffseal
#wptrans
logos-creative.com/
     wcatl
LOL WUTAPI?
is the Transients
The Transients API
“offers a simple and standardized
way of storing cached data in the
database temporarily by giving it a
custom name and a timeframe after
which it will expire and be deleted.”
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)

               Persistent
Transient                     Persistent (varies)
              (database)

            Non-persistent
 Cache                        Persistent (varies)
              (memory)
                                              Thanks to Rarst.
thetransientsAPI




         Tweets             Friends                Scrobbles

                  Options API: Username, URL, ID



          externalAPIs
thetransientsAPI




         Tag Cloud   Ratings   Custom Queries




      expensivequeries
3
mainfunctions
mainfunctions

        set_transient(
           $transient,
           $value,
           $expiration
        );
         set_transient
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
mainfunctions


$value
✓   (array|object) Data to save, either a regular variable or an
    array/object

✓   Handles serialization of complex data for you



        set_transientargs
mainfunctions


$expiration
✓   (integer) number of seconds to keep the data before
    refreshing

✓   Example: 60*60*24 or 86400 (24 hours)



       set_transientargs
mainfunctions



MINUTE_IN_SECONDS   =   60 (seconds)
HOUR_IN_SECONDS     =   60 * MINUTE_IN_SECONDS
DAY_IN_SECONDS      =   24 * HOUR_IN_SECONDS
WEEK_IN_SECONDS     =   7 * DAY_IN_SECONDS
YEAR_IN_SECONDS     =   365 * DAY_IN_SECONDS



        timeconstants
mainfunctions


get_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
mainfunctions




delete_transient($transient);



      delete_transient
mainfunctions


 set_site_transient();
 get_site_transient();
delete_site_transient();
                These work ‘network wide’.


          wpmultisite
3
exampleusecases
cachetagcloud
cachetagcloud

function 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;

}
EXPERT

MODE
cachetagcloud

function edit_term_delete_tag_cloud() {

    delete_transient( 'my_tag_cloud' );

}

add_action( 'edit_post', 'edit_term_delete_tag_cloud' );
cachemyissues
cachemyissues
function 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;
}
EXPERT

MODE
cachemyissues
function 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' );
cachebigquery
cachebigquery
function 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;
}
cachebigquery

function delete_query_for_commenters() {

    delete_transient( 'top_commenters_cached' );

}

add_action( 'comment_post', 'delete_query_for_commenters' );
cachebigquery
function 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;
}
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();
}
cachebigquery

function clear_popular_posts() {

    for ( $i = 0; $i < 50; $i++ ) {

        delete_transient( 'popular_posts' . $i );

    }

}

add_action( 'edit_post', 'clear_popular_posts' );
EXPERT

MODE
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.
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();
    }
}
cachebigquery
function 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' );
}
TOP OF HACKER NEWS


  CONQUERED
4
warnings
expiry&garbagecollection


✓ everything works on request
✓ expired != deleted, unless requested
✓ unrequested, undeleted transients stay
  until you remove them explicitly
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)
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
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)
3
usefultools
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
?
questions
logos-creative.com/
     wcatl

Weitere ähnliche Inhalte

Was ist angesagt?

MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APISix Apart KK
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks Damien Seguy
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Gta v savegame
Gta v savegameGta v savegame
Gta v savegamehozayfa999
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Masahiro Nagano
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2zfconfua
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPressMaor Chasen
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application frameworkDustin Filippini
 
A Tour to MySQL Commands
A Tour to MySQL CommandsA Tour to MySQL Commands
A Tour to MySQL CommandsHikmat Dhamee
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 
The Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryChris Olbekson
 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in DoctrineJonathan Wage
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指すYasuo Harada
 

Was ist angesagt? (20)

MTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new APIMTDDC 2010.2.5 Tokyo - Brand new API
MTDDC 2010.2.5 Tokyo - Brand new API
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
PHP tips and tricks
PHP tips and tricks PHP tips and tricks
PHP tips and tricks
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Gta v savegame
Gta v savegameGta v savegame
Gta v savegame
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
Intro to advanced caching in WordPress
Intro to advanced caching in WordPressIntro to advanced caching in WordPress
Intro to advanced caching in WordPress
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
WordPress as an application framework
WordPress as an application frameworkWordPress as an application framework
WordPress as an application framework
 
A Tour to MySQL Commands
A Tour to MySQL CommandsA Tour to MySQL Commands
A Tour to MySQL Commands
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
The Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the QueryThe Query the Whole Query and Nothing but the Query
The Query the Whole Query and Nothing but the Query
 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in Doctrine
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 

Ähnlich wie Speed Things Up with Transients

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Jeff Carouth
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownpartsBastian Feder
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
WordPress Transients
WordPress TransientsWordPress Transients
WordPress TransientsTammy Hart
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsBastian Feder
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)tompunk
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helperslicejack
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...andrewnacin
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsPierre MARTIN
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Evgeny Nikitin
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony TechniquesKris Wallsmith
 

Ähnlich wie Speed Things Up with Transients (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4Can't Miss Features of PHP 5.3 and 5.4
Can't Miss Features of PHP 5.3 and 5.4
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
WordPress Transients
WordPress TransientsWordPress Transients
WordPress Transients
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)Apostrophe (improved Paris edition)
Apostrophe (improved Paris edition)
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
WordCamp San Francisco 2011: Transients, Caching, and the Complexities of Mul...
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014Lazy evaluation drupal camp moscow 2014
Lazy evaluation drupal camp moscow 2014
 
Advanced symfony Techniques
Advanced symfony TechniquesAdvanced symfony Techniques
Advanced symfony Techniques
 

Mehr von Cliff Seal

Trust in the Future
Trust in the FutureTrust in the Future
Trust in the FutureCliff Seal
 
Building Advocates with World-Class Customer Experiences
Building Advocates with World-Class Customer ExperiencesBuilding Advocates with World-Class Customer Experiences
Building Advocates with World-Class Customer ExperiencesCliff Seal
 
Mastering B2B Email
Mastering B2B EmailMastering B2B Email
Mastering B2B EmailCliff Seal
 
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-Done
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-DoneDeath to Boring B2B Marketing, Part 2: Jobs-to-Be-Done
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-DoneCliff Seal
 
DIY WordPress Site Management: Configure, Launch, and Maintain
DIY WordPress Site Management: Configure, Launch, and MaintainDIY WordPress Site Management: Configure, Launch, and Maintain
DIY WordPress Site Management: Configure, Launch, and MaintainCliff Seal
 
Inviting Experimentation by Design
Inviting Experimentation by DesignInviting Experimentation by Design
Inviting Experimentation by DesignCliff Seal
 
Death to Boring B2B Marketing: How Applying Design Thinking Drives Success
Death to Boring B2B Marketing: How Applying Design Thinking Drives SuccessDeath to Boring B2B Marketing: How Applying Design Thinking Drives Success
Death to Boring B2B Marketing: How Applying Design Thinking Drives SuccessCliff Seal
 
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)Cliff Seal
 
People Over Pixels: Meaningful UX That Scales
People Over Pixels: Meaningful UX That ScalesPeople Over Pixels: Meaningful UX That Scales
People Over Pixels: Meaningful UX That ScalesCliff Seal
 
Friendlier, Safer WordPress Admin Areas
Friendlier, Safer WordPress Admin AreasFriendlier, Safer WordPress Admin Areas
Friendlier, Safer WordPress Admin AreasCliff Seal
 
Meaningful UX At Any Scale
Meaningful UX At Any ScaleMeaningful UX At Any Scale
Meaningful UX At Any ScaleCliff Seal
 
No one cares about your content (yet): WordCamp Charleston 2014
No one cares about your content (yet): WordCamp Charleston 2014No one cares about your content (yet): WordCamp Charleston 2014
No one cares about your content (yet): WordCamp Charleston 2014Cliff Seal
 
Usability, Groupthink, and Authority
Usability, Groupthink, and AuthorityUsability, Groupthink, and Authority
Usability, Groupthink, and AuthorityCliff Seal
 
Get Started in Professional WordPress Design & Development
Get Started in Professional WordPress Design & DevelopmentGet Started in Professional WordPress Design & Development
Get Started in Professional WordPress Design & DevelopmentCliff Seal
 
No One Cares About Your Content (Yet): WordCamp Chicago 2013
No One Cares About Your Content (Yet): WordCamp Chicago 2013No One Cares About Your Content (Yet): WordCamp Chicago 2013
No One Cares About Your Content (Yet): WordCamp Chicago 2013Cliff Seal
 
No One Cares About Your Content (Yet): WordCamp Miami 2013
No One Cares About Your Content (Yet): WordCamp Miami 2013No One Cares About Your Content (Yet): WordCamp Miami 2013
No One Cares About Your Content (Yet): WordCamp Miami 2013Cliff Seal
 
A Brief History of Metal
A Brief History of MetalA Brief History of Metal
A Brief History of MetalCliff Seal
 
No One Cares About Your Content (Yet): WordCamp Phoenix 2013
No One Cares About Your Content (Yet): WordCamp Phoenix 2013No One Cares About Your Content (Yet): WordCamp Phoenix 2013
No One Cares About Your Content (Yet): WordCamp Phoenix 2013Cliff Seal
 
WordPress and Pardot: The World’s Newest Power Couple
WordPress and Pardot: The World’s Newest Power CoupleWordPress and Pardot: The World’s Newest Power Couple
WordPress and Pardot: The World’s Newest Power CoupleCliff Seal
 
No One Cares About Your Content (Yet): Digital Atlanta 2012
No One Cares About Your Content (Yet): Digital Atlanta 2012No One Cares About Your Content (Yet): Digital Atlanta 2012
No One Cares About Your Content (Yet): Digital Atlanta 2012Cliff Seal
 

Mehr von Cliff Seal (20)

Trust in the Future
Trust in the FutureTrust in the Future
Trust in the Future
 
Building Advocates with World-Class Customer Experiences
Building Advocates with World-Class Customer ExperiencesBuilding Advocates with World-Class Customer Experiences
Building Advocates with World-Class Customer Experiences
 
Mastering B2B Email
Mastering B2B EmailMastering B2B Email
Mastering B2B Email
 
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-Done
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-DoneDeath to Boring B2B Marketing, Part 2: Jobs-to-Be-Done
Death to Boring B2B Marketing, Part 2: Jobs-to-Be-Done
 
DIY WordPress Site Management: Configure, Launch, and Maintain
DIY WordPress Site Management: Configure, Launch, and MaintainDIY WordPress Site Management: Configure, Launch, and Maintain
DIY WordPress Site Management: Configure, Launch, and Maintain
 
Inviting Experimentation by Design
Inviting Experimentation by DesignInviting Experimentation by Design
Inviting Experimentation by Design
 
Death to Boring B2B Marketing: How Applying Design Thinking Drives Success
Death to Boring B2B Marketing: How Applying Design Thinking Drives SuccessDeath to Boring B2B Marketing: How Applying Design Thinking Drives Success
Death to Boring B2B Marketing: How Applying Design Thinking Drives Success
 
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)
Introducing WordPress Multitenancy (Wordcamp Vegas/Orlando 2015/WPCampus)
 
People Over Pixels: Meaningful UX That Scales
People Over Pixels: Meaningful UX That ScalesPeople Over Pixels: Meaningful UX That Scales
People Over Pixels: Meaningful UX That Scales
 
Friendlier, Safer WordPress Admin Areas
Friendlier, Safer WordPress Admin AreasFriendlier, Safer WordPress Admin Areas
Friendlier, Safer WordPress Admin Areas
 
Meaningful UX At Any Scale
Meaningful UX At Any ScaleMeaningful UX At Any Scale
Meaningful UX At Any Scale
 
No one cares about your content (yet): WordCamp Charleston 2014
No one cares about your content (yet): WordCamp Charleston 2014No one cares about your content (yet): WordCamp Charleston 2014
No one cares about your content (yet): WordCamp Charleston 2014
 
Usability, Groupthink, and Authority
Usability, Groupthink, and AuthorityUsability, Groupthink, and Authority
Usability, Groupthink, and Authority
 
Get Started in Professional WordPress Design & Development
Get Started in Professional WordPress Design & DevelopmentGet Started in Professional WordPress Design & Development
Get Started in Professional WordPress Design & Development
 
No One Cares About Your Content (Yet): WordCamp Chicago 2013
No One Cares About Your Content (Yet): WordCamp Chicago 2013No One Cares About Your Content (Yet): WordCamp Chicago 2013
No One Cares About Your Content (Yet): WordCamp Chicago 2013
 
No One Cares About Your Content (Yet): WordCamp Miami 2013
No One Cares About Your Content (Yet): WordCamp Miami 2013No One Cares About Your Content (Yet): WordCamp Miami 2013
No One Cares About Your Content (Yet): WordCamp Miami 2013
 
A Brief History of Metal
A Brief History of MetalA Brief History of Metal
A Brief History of Metal
 
No One Cares About Your Content (Yet): WordCamp Phoenix 2013
No One Cares About Your Content (Yet): WordCamp Phoenix 2013No One Cares About Your Content (Yet): WordCamp Phoenix 2013
No One Cares About Your Content (Yet): WordCamp Phoenix 2013
 
WordPress and Pardot: The World’s Newest Power Couple
WordPress and Pardot: The World’s Newest Power CoupleWordPress and Pardot: The World’s Newest Power Couple
WordPress and Pardot: The World’s Newest Power Couple
 
No One Cares About Your Content (Yet): Digital Atlanta 2012
No One Cares About Your Content (Yet): Digital Atlanta 2012No One Cares About Your Content (Yet): Digital Atlanta 2012
No One Cares About Your Content (Yet): Digital Atlanta 2012
 

Speed Things Up with Transients

  • 1. speed things up with transients
  • 4. LOL WUTAPI? is the Transients
  • 5. The Transients API “offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted.”
  • 6. The Transients API ✓ like Options API, but with expiration ✓ uses fast memory (if configured) ✓ uses database otherwise
  • 7. Native Object Cache Plugin Persistent Option N/A (database) Persistent Transient Persistent (varies) (database) Non-persistent Cache Persistent (varies) (memory) Thanks to Rarst.
  • 8. thetransientsAPI Tweets Friends Scrobbles Options API: Username, URL, ID externalAPIs
  • 9. thetransientsAPI Tag Cloud Ratings Custom Queries expensivequeries
  • 11. mainfunctions set_transient( $transient, $value, $expiration ); set_transient
  • 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. 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. mainfunctions $expiration ✓ (integer) number of seconds to keep the data before refreshing ✓ Example: 60*60*24 or 86400 (24 hours) set_transientargs
  • 15. mainfunctions MINUTE_IN_SECONDS = 60 (seconds) HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS timeconstants
  • 16. mainfunctions get_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
  • 21. cachetagcloud function 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; }
  • 23. cachetagcloud function edit_term_delete_tag_cloud() { delete_transient( 'my_tag_cloud' ); } add_action( 'edit_post', 'edit_term_delete_tag_cloud' );
  • 25. cachemyissues function 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; }
  • 27. cachemyissues function 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' );
  • 29. cachebigquery function 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. cachebigquery function delete_query_for_commenters() { delete_transient( 'top_commenters_cached' ); } add_action( 'comment_post', 'delete_query_for_commenters' );
  • 31. cachebigquery function 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. 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. cachebigquery function clear_popular_posts() { for ( $i = 0; $i < 50; $i++ ) { delete_transient( 'popular_posts' . $i ); } } add_action( 'edit_post', 'clear_popular_posts' );
  • 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. 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. cachebigquery function 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. TOP OF HACKER NEWS CONQUERED
  • 40.
  • 41. expiry&garbagecollection ✓ everything works on request ✓ expired != deleted, unless requested ✓ unrequested, undeleted transients stay until you remove them explicitly
  • 42. 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)
  • 43. 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
  • 44. 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)
  • 46. 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