Dreb Bits

Tag: Varnish

Purge Varnish Cache on Save

In case, someone out there trying to figure out how to purge varnish (3.x) cache in your WordPress site when updating a post/page — I’ve dealt with it this week and it’s pretty easy to accomplish it.

Now that we’re talking about purging the cache, I presumed you have varnish configured and all your setup works. To start off, if there’s no definition of purging in your vcl file, you might want to add them — https://www.varnish-cache.org/docs/3.0/tutorial/purging.html. Remember to sudo service varnish restart after modifying the file so the changes will take effect.

Now in your ever lovely WordPress:


/** * Purge Varnish cache on save * * @param int $post_id Post ID. */ function awesome_save_post( $post_id ) { wp_remote_request( esc_url( get_permalink( $post_id ) ), array( 'method' => 'PURGE' ) ); // Or store the response if you'd like to verify it further. } add_action( 'save_post', 'awesome_save_post' );

You can pop that in in your code if you only need to invalidate cache for content. For a verbose invalidation such as commenting or deleting an item and when changing themes, checkout Varnish HTTP Purge that is readily available in WordPress plugin repo.