Dougal Campbell's geek ramblings

WordPress, web development, and world domination.

Using the WordPress Object Cache

I’ve been planning to write up a plugin to serve as an example of using the WordPress Object Cache, but haven’t had time to finish it up. However, this topic came up on the wp-hackers mailing list recently, so I thought that I would go ahead and give a brief rundown on how to use the cache from within your own plugins.

The goal of the WordPress Object Cache is to provide a way to persistently store results from expensive queries in an external cache file. This lets us avoid re-querying the database or re-fetching information from an external web service if we think that the data hasn’t changed. It should be noted, however, that some server environments have trouble using the cache. It is up to you to monitor your server to determine whether use of the cache will benefit your sites,

Using the object cache is actually quite simple. You write data to the cache using wp_cache_set(), and you read cached data with wp_cache_get().

Before I get to the sample code, there are some other things you’ll need to check. The object cache is disabled by default. In order to enable it, you’ll need to edit your wp-config.php file. Add the following lines, after the setting for WP_LANG:


// Enable the WordPress Object Cache:
define(ENABLE_CACHE, true);

Also, make sure that there is not a define for a DISABLE_CACHE constant. In addition, you will need to make sure that you have a wp-content/cache subdirectory on your host, and that it is writable by your web server process. I assume that if you are planning to write code to use the object cache, that you know how to handle this on your host server.

That said, let’s take a look at how you use the wp_cache_get() and wp_cache_set() functions in your own code. First, we’ll examine how we put data into the cache. Think of the cache as a set of containers, each of which can store several data packets. You can name the containers and the packets within, so that you know how to retrieve them later. In these examples, I am naming the container mycache, and we’ll call the data packet mysettings. It would probably be a good convention to name your own container based on the name of your plugin, and name the packets based on what kind of information you are storing (e.g. userdata or popularpostinfo).

Here’s how we write data to the cache:


  // Whenever we need to rewrite the cache data:
  // This could be calling a database, webservice, etc.
  $mydata = my_complicated_data_query(); 
  $myexpire = 60 * 60 * 24; // Cache data for one day (86400 seconds)
  wp_cache_set('mysettings', $mydata, 'mycache', $myexpire);

You’ll have to determine the best point in your code to do this depending on what kind of data you’re caching. For example, if you are caching user profile data, you might want to update the cache anytime a user’s profile changes by hooking into the profile_update() API hook.

Now, when you want to avoid that complicated database query, check the cache first. If your information is not already in the cache, or if it has expired, wp_cache_get() will return false. In that case, you’ll need to re-query the database for the information. Otherwise, it will return whatever data structure that you previously stored.


  // First of all, before you try to access the user data, check
  // the cache.
  $mydata = wp_cache_get('mysettings', 'mycache');

  if (false === $mydata) {
    // The cache data doesn't exist or it's expired. 
    // Do whatever we need to populate $mydata from the
    // database normally... 
    
    $mydata = my_complicated_data_query();

    // Since we know that the cache isn't up to date, we should
    // write this fresh information to it now, so that we can avoid
    // the query next time.
    $myexpire = 60 * 60 * 24; // Cache data for one day (86400 seconds)
    wp_cache_set('mysettings', $mydata, 'mycache', $myexpire);
  }

It’s up to you to decide an appropriate amount of time to cache your data and to determine which API action hooks should trigger cache updates. A whole day will be too long for some types of information. But with this basic information in hand, it should be relatively easy for plugin authors to take advantage of the object cache.

About Dougal Campbell

Dougal is a web developer, and a "Developer Emeritus" for the WordPress platform. When he's not coding PHP, Perl, CSS, JavaScript, or whatnot, he spends time with his wife, three children, a dog, and a cat in their Atlanta area home.
This entry was posted in Development, Plugins, WordPress and tagged , , , , . Bookmark the permalink.

18 Responses to Using the WordPress Object Cache

  1. ketsugi says:

    How well does this work for caching binary information, like gravatars for example? Can you give example code on how to do this?

  2. CountZero says:

    I suppose this can be useful especially in connection with AJAX enhancements. I’ll take a closer look on this topic for my future developments. Thanks for the information about the caching mechanism in WP2 ;)

  3. Pingback: jawe.net » Blog Archiv » Links vom Sonntag, 23. Juli 2006

  4. Dougal says:

    ketsugi: you can cache any data that can be held in a PHP variable. However, I don’t think you’d gain anything by trying to cache gravatar icons. Even if your plugin is storing local copies on your server, apache would probably be doing its own caching of a sort, by returning “304 Not Modified” status to browsers who had already fetched the image previously.

  5. Mark Jaquith says:

    One of the biggest misconceptions is that the object cache invalidates the need for an output (HTML) cache. It doesn’t. The object cache saves a few MySQL queries and a few PHP cycles structuring the results of those queries, but it still leaves many queries for MySQL, and it still requires that WordPress be fully loaded for each hit. WP-Cache2 is still extremely useful for caching your HTML output.

    It should also be noted that not everyone will benefit from using the built-in disk-based object cache. I strongly suggest that you measure execution time and compare. If you have full access to your server (dedicated or virtual), I suggest you look into alternative storage engines for the object cache, such as the ones using Memcached or APC, as this data will return more quickly than from the disk cache.

  6. David Chait says:

    I just wanted to chime in full agreement with Mark. Generally the object cache should NOT be used, unless you know your server setup and performance factors VERY well. It has even been proven detrimental (seriously in certain instances) on shared hosting setups. If you have a dedicated server, then the alternative memory cache engines become useful — but only if you aren’t already running a mysql query cache of a decent size… ;)

  7. Dougal says:

    Mark and David,

    Thanks for pointing out more details on possible downsides to using the object cache. I didn’t want to sidetrack into that tangent in my article, partially to keep it short, and partially because I’m not familiar myself with just what factors might be involved. Personally, I am on a dedicated server (at least for all practical purposes), and the object cache works fine for me. But I also use WP-Cache2, MySQL query caching, and the APC PHP opcode cache.

    One other thing I’ll reiterate, though, is that a good use for the object cache is to keep a local store of information fetched from an external web service, if you don’t want to stick it into a database table.

  8. Pingback: smackfoo › Using the WordPress Object Cache

  9. Stephen Chu says:

    Great article. Thanks. I’ve been using the object cache to reduce the number of DB queries on my site. It did help in my shared hosting setup by avoiding expensive queries to the overloaded mySQL server before the host upgraded the hardware.

    One note thought. The expire parameter is not used at all. WP_Object_Cache->set simply ignores it. The only way to have object specific expiration time is to have your own WP_Object_Cache object.

  10. Pingback: Using the WordPress Object Cache › smackfoo.com

  11. Pingback: Der WordPress Object Cache at marcO’s_br4inh4ck

  12. Pingback: 使用 WordPress 对象缓存

  13. Pingback: 深蓝海 » Blog Archive » 其实我用的插件都算是蛮多了

  14. Pingback: WordPress 2.5 Cache - bueltge.de [by:ltge.de]

  15. Pingback: ??????????? ? WordPress (1/3)

  16. Pingback: XCache Object Cache Plugin for WordPress 2.5+ :: geek ramblings

  17. Pingback: XCache Object Cache Plugin for WordPress 2.5+ | Wordpress Blog NL

  18. Pingback: ?????… » WordPress?????????????????????????

Leave a Reply

%d bloggers like this: