Fragment caching in WordPress to optimize site speed for logged-in users
23 September 2013
If you’re like us, you’re probably using WordPress for much more than its original purpose of powering a simple blog. Many of the WordPress sites we build have extensive social features, allowing people to login, create a profile, and interact with other users. Unfortunately, most of the available caching plugins assume that your site will only be cached for anonymous users, because the logged-in users will undoubtedly have some areas of the page tailored to their personal experience; the simplest example being the standard, “Welcome, [username]” with a link to logout. So how can we provide a cached experience for all users and prevent the site from performing expensive and slow-loading page queries?
Enter fragment caching. The concept is to take particular pieces of the page where a lot of heavy server-side lifting is being done and store that in a cache for later retrieval. The next time you load the page, those areas will be loaded from the cache (bypassing the need to perform hundreds of database queries) and quickly rendered. The huge upside here is that you can leave particular areas untouched by caching (e.g. the aforementioned “Welcome [username]” header) and pick and choose which parts of the page will benefit from being cached.
Mark Jaqith, a lead developer on the WordPress team, posted an example on his blog of how to perform basic fragment caching. We’ve taken his example one step further and turned it into a plugin to make it even easier to integrate into your site.
The plugin also has the option of using a filesystem-based cache when you don’t have an object cache available. This means it requires completely minimal setup and can be run on pretty much any server platform. For more on that, see the WordPress documentation on object caching.
To use it, you simply need to wrap the area of your page that you’d like to cache by instantiating a FragmentCache variable, first calling the output() method (which will output the cached content if it’s found) and then calling the store() method at the end (which will store the data for the next page visit), like so:
<?php $cache = new FragmentCache(); if ( ! $cache->output() ): ?> <div> <h1>My Cached Content</h1> <?php output_expensive_queries(); ?> </div> <?php $cache->store(); endif; ?>
For more info and documentation, go check out the plugin!