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.

Stumble It!
Using the WordPress Object Cache

Related posts:

  1. XCache Object Cache Plugin for WordPress 2.5+
    "[drain file 16 show default_show] This is another one of those articles that will be of interest to a minority of WordPress users. In particular,..."
  2. WP-Cache fix for Content-Type in feeds
    " If you run a busy WordPress site, or even if your site just has a lot of processor-intensive plugins, then you probably already run..."
  3. W3 Total Cache Plugin
    " There’s a new WordPress cache plugin in town, and it’s called W3 Total Cache. This plugin is one of the contestants in the 2009..."
  4. My Favorite WordPress Plugins
    " One of the coolest things about WordPress is the powerful Plugin API which allows us to create add-ons which can radically extend the basic..."
  5. Text Filter Suite Plugin for WordPress
    "Since Talk Like a Pirate Day is only three weeks away, I spent some time this weekend revamping my old Fun Filters hack. The result..."
This entry was posted in Development, Plugins, WordPress and tagged , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

7 Comments

  1. ketsugi ketsugi.com
    Posted July 22, 2006 at 12:15 am | Permalink

    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 4null4.de
    Posted July 23, 2006 at 9:01 am | Permalink

    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. Dougal dougal.gunters.org
    Posted July 25, 2006 at 12:53 pm | Permalink

    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.

  4. Mark Jaquith txfx.net
    Posted July 25, 2006 at 4:40 pm | Permalink

    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.

  5. David Chait chait.net
    Posted July 25, 2006 at 4:53 pm | Permalink

    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… ;)

  6. Dougal dougal.gunters.org
    Posted July 25, 2006 at 9:53 pm | Permalink

    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.

  7. Stephen Chu ju-ju.com
    Posted September 19, 2006 at 3:48 pm | Permalink

    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 Trackbacks

  1. [...] geek ramblings » Using the WordPress Object Cache Tags: dev web wordpress [...]

  2. By smackfoo › Using the WordPress Object Cache on August 1, 2006 at 11:15 pm

    [...] Using the WordPress Object Cache [...]

  3. [...] Using the WordPress Object Cache [...]

  4. By Der WordPress Object Cache at marcO’s_br4inh4ck on November 16, 2007 at 1:18 am

    [...] geek ramblings » Using the WordPress Object Cache [...]

  5. By 使用 WordPress 对象缓存 on January 23, 2008 at 8:59 am

    [...] 其实我用的插件都算是蛮多了,达到了15个(当然也有些疯子,装了30多个插件,然后怪 WordPress 太慢。)。但是最近经过我的优化之外,其实博客的速度也不算太慢了,这里其中我就用到就是 WordPress 缓存机制,以前我经常用的是 WP-Corn 的定时更新的功能进行缓存。今天给大家介绍另外一种缓存机制:WordPress Object Cache。以下信息节选翻译自:Using the WordPress Object Cache [...]

  6. [...] 其实我用的插件都算是蛮多了,达到了15个(当然也有些疯子,装了30多个插件,然后怪 WordPress 太慢。)。但是最近经过我的优化之外,其实博客的速度也不算太慢了,这里其中我就用到就是 WordPress 缓存机制,以前我经常用的是 WP-Corn 的定时更新的功能进行缓存。今天给大家介绍另外一种缓存机制:WordPress Object Cache。以下信息节选翻译自:Using the WordPress Object Cache [...]

  7. By WordPress 2.5 Cache - bueltge.de [by:ltge.de] on April 28, 2008 at 5:36 am

    [...] Nutzung in eigenen Funktionen [...]

  8. By ??????????? ? WordPress (1/3) on June 24, 2008 at 10:52 pm

    [...] ????? ????????? WordPress Object Cache, ?????????? ?????????? ????????? “ENABLE_CACHE” – define(’ENABLE_CACHE’, true);. ????? ???? ? ?????????? wp-content ??????? ??????? ????? cache, ??? ???? ??? ?????? ?????????? ????? ????????? ????? ?? ?????? ???????????? ?? ????? ???????? ???????? ???-??????. ??? ?????? ? ?????? ?????????? ???????????? ???????: wp_cache_set(), wp_cache_get(). ??? ??? ? ?? ???????? ????? ???????? ?????? ?? Object Cache, ?????????? ???????????? ?? ??????? Using the WordPress Object Cache. [...]

  9. [...] For more information, see my previous article, Using the WordPress Object Cache. [...]

  10. [...] For more information, see my previous article, Using the WordPress Object Cache. [...]

Post a Comment

Your email is never published nor shared.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Subscribe without commenting

  • Subscribe

  • Follow Me

    Twitter  Facebook  Flickr  Last.fm  LinkedIn  StumbleUpon  Technorati  Delicious  
    • icon
  • Referrals

    Sign up for Text Link Ads and earn money from your blog.
  • Lifestream

    • Anybody know where I can get an apt for PHP > 5.2.6 for Ubuntu Jaunty (without upgrading to Karmic?) [dougal]
      1h ago via Twitter
    • Crap. A bug in the Unbuntu 9.04 version of PHP has caused me to waste several hours. I hate when that happens. [dougal]
      1h ago via Twitter
    • Every time the @BaskinRobbins "Ice Cream and Cake" commercial comes on, our kids all break into spontaneous song and dance. Hilarious! [dougal]
      19h ago via Twitter
    • Today for me will be all about XML. I'm trying to maintain a positive attitude about that :) [dougal]
      1d ago via Twitter
    • @ryanolson I'll be working on a new version of the Fancybox Gallery plugin soon, with user-configurable options. [dougal]
      1d ago via Twitter