Clearing The Cache When A Widget Is Saved

November 30th, 2011 by Stephen Cronin (Please wait) [Shortlink]

WP Super Cache has a setting which allows the cache to be cleared when a post is saved. I needed to clear the cache when a widget is saved. It turned out to be surprisingly easy.

Simply add the following code to functions.php or your custom WordPress plugin:

add_filter( 'widget_update_callback', 'sjc_widget_save', 10, 3 );
function sjc_widget_save( $instance, $new_instance, $old_instance, $this ) {
	// if WP Super Cache is being used, clear the cache
	global $file_prefix;
	if ( function_exists( 'wp_cache_clean_cache' ) ) wp_cache_clean_cache( $file_prefix );
	// don't forget to return the widget content
	return $instance;
}

The code above will clear the entire cache any time a widget is saved. If you only want to clear the cache when a particular widget is saved, you will need to add a conditional that searches for something identifying the widget in the widget content ($instance), for example:

add_filter( 'widget_update_callback', 'sjc_widget_save', 10, 3 );
function sjc_widget_save( $instance, $new_instance, $old_instance, $this ) {
	if ( stristr( $instance, 'my identifying string' ) ) {
		// if WP Super Cache is being used, clear the cache
		global $file_prefix;
		if ( function_exists( 'wp_cache_clean_cache' ) ) wp_cache_clean_cache( $file_prefix );
	}
	// don't forget to return the widget content
	return $instance;
}

This method utilises the widget_update_callback filter, which is largely undocumented. We’re not actually filtering the widget content, we’re just returning it unchanged. In effect, we’re using the hook as an action rather than a filter, but it achieves our goal.

This filter will work for all of the built-in widgets, but may not work for widgets created by plugins depending on how they were created.

This will only work for the WP Super Cache plugin, which is what the client I am working for uses. I actually use W3 Total Cache on this site, but haven’t looked into how to do this with W3TC. If I ever get around to that, I’ll update this post.

I also need to point out that this code works by using a function that is part of WP Super Cache. As such, although it works with the current version of WP Super Cache, there is no guarantee that future versions will not include changes that break this.

Like this article? Plus One it!

Tags: , , ,

There is 1 reponse to this article. Visit the comments page.

Leave a Reply

Anti-Spam Quiz:


Stephen Cronin

is Manager of Online Service Delivery at a Queensland Government department & has been a freelance WordPress developer/consultant since 2007
*Content on this site is my own and is not related to my employer

Hire me - I'm expensive, but I'm very good!

WordPress Plugins

Want a Custom WordPress plugin? See my Services page.

Greasemonkey Scripts

Visit my home page at Userscripts.org.