[wp-hackers] Best Practices for Caching Plugin WidgetOutput?

Peter Westwood peter.westwood at ftwr.co.uk
Wed Dec 24 06:58:31 GMT 2008

Mike Schinkel wrote:
> I'm wondering if there are any best practices for caching output generated
> by a plugin widget?
> I have written a simple plugin for a client that collects the top 10
> categories in descending order based on a count of the number of posts. Of
> course it doesn't make sense to run that SQL query for every page load.  I
> could generate the list and then write it to a text file somewhere and read
> from in instead to cache but I'm wondering if there is not a "standard" way
> to cache the output?
> Also I could just refresh periodically (hourly?) or maybe hooking when a
> post is added/updated and/or a category applied/removed; suggestions on
> this?
My recommendation(s) would be:

Cache the data in an option.

Don't bother with using the object cache as well the options code will 
be using it anyway.

If your widget is configurable and supports multiple instances ensure that you key your cache based on the config data so that you have a cache entry per widget - something like naming the options mywidget_{md5($config_data)}

Invalidate the cache based on user-actions which require it to be
invalidated - i.e. hook into the relevant actions for post <>
category relationship updates

It is much better to invalidate the cache on a user trigger of change than periodically especially when the data will only change at the point.

Peter Westwood
http://blog.ftwr.co.uk | http://westi.wordpress.com
C53C F8FC 8796 8508 88D6 C950 54F4 5DCD A834 01C5 

More information about the wp-hackers mailing list