The other day I talked about updating another post’s meta. That’s all well and good, but what happens when you’ve cached that other page?

Most cache tools work via the simplistic understanding that if you edit a page, you want to empty the cache for that page. The problem with my clever post-meta updating is that doesn’t actually update the post. Oh, sure it updates the data, but that doesn’t perform an update in a way that most plugins understand.

Thankfully this can be done programmatically in a few different ways, depending on what plugin is used.

  1. Tell Varnish to empty the page’s cache any time post meta is updated
  2. Add a force-empty command to the function that updates the meta

Using Varnish HTTP Purge

Since I’m running on DreamPress, my plugin of choice is Varnish HTTP Purge. This is a very simple plugin that has no real interface by design. Mike Schroder and I picked it for use because of it’s beautiful simplicity, and when it was abandoned, adopted it. I’m rather well acquainted with it and at the behest of others, I wrote in code where people could add extra URLs to flush as well as extra events to trigger. There’s even a wiki doc about it.

However. That’s not what I did here because I wanted to limit when it runs as much as possible.

When To Empty Cache

There’s a part of caching that is always difficult to manage. When should a page be emptied and when should a whole section of pages be emptied? The obvious answer is that we should retain a cache as long as possible, emptying select pages only when necessary.

With WordPress posts and pages it’s pretty easy to know “Update the post, empty the cache.” But when you start talking about things like the JSON API, it’s a lot harder. Most plugins handle the JSON API for you, but if you’ve built your own API (like say /wp-json/lwtv/) and built out a lot of custom APIs (like say stats or an Alexa skill) you will want to flush that whole darn thing every single time.

The Code

Okay so how do we do that easily?

In the function I showed you the other day, I added this right before the re-hook at the end:

if ( class_exists( 'VarnishPurger' ) ) {
	$varnish_purge = new VarnishPurger();
	$varnish_purge->purgeUrl( get_permalink( $post_id ) );

That makes sure the Varnish plugin is running and calls a URL to flush. Done. If you want to have it do more URLs, you can do this:

if ( class_exists( 'VarnishPurger' ) ) {
	$purgeurls = array( 
		get_permalink( $post_id ) . '?vhp-regex',
		get_site_url() . '/page1/',
		get_site_url() . '/custom_page/',
		get_site_url() . '/wp-json/lwtv/?vhp-regex',
	foreach ( $purgeurls as $url ) {
		$this->varnish_purge->purgeUrl( $url ) ;

And then you can add in as many as you want.

Reader Interactions

%d bloggers like this: