Purging additional paths when clearing cache.

Modify paths to be purged when a clear cache operation is performed.

T
Written by Team Pressidium
Updated over a week ago

Purging additional paths

If you need to purge additional paths, you can hook into the pressidium_purge_page_cache filter (Read more on Pressidium specific WordPress actions and filters). You can add this functionality in your functions.php file or in a custom plugin.

This is an advanced operation and care should be taken to not specify an overly broad set of paths since this will negatively affect the performace of your website.

Sample code to add paths to be purged to the existing path list:

/**
* Filter computed paths that are going to be purged.
*
* @param array $paths Paths to be purged.
*
* @return array
*/
function mycustom_purge_additional_paths( $paths ) {
$paths[] = '^/foo/';
$paths[] = '^/bar/';

return $paths;
}

add_filter( 'pressidium_purge_page_cache', 'mycustom_purge_additional_paths' );

Paths are regular expressions

We strongly recommend to use the ^ and/or $ anchor tokens to match the beginning and end of a path (check out regex101 to test your regular expressions).

Most paths should begin with the ^ token to match the beginning of the path.

  • /foo/ will invalidate /foo/, /foo/bar/, and /baz/foo/.

  • ^/foo/ will invalidate /foo/ and /foo/bar/, but it won't invalidate /baz/foo/.

You can inspect the post(s) that triggered the cache purge operation by looking into the second parameter of the filter. It contains an array of post IDs that can be used to get additional post information.

Sample code to add paths to be purged depending on post type:

/**
* Filter computed paths that are going to be purged.
*
* @param array $paths Paths to be purged.
* @param array $post_ids IDs of the posts/pages to be purged.
*
* @return array
*/
function mycustom_purge_additional_paths( $paths, $post_ids ) {
foreach ( $post_ids as $post_id ) {
$post = get_post( $post_id );

switch ( $post->post_type ) {
case 'post':
$paths[] = '^/foo/';
break;
case 'my_custom_post_type':
$paths[] = '^/bar/';
break;
default:
break;
}
}

// Return unique paths
return array_values( array_unique( $paths ) );
}

add_filter( 'pressidium_purge_page_cache', 'mycustom_purge_additional_paths', 10, 2 );

Did this answer your question?