Skip to content

Clearing the Cache Dynamically

Raam Dev edited this page Feb 17, 2015 · 10 revisions

Clear entire cache when saving any post

You can call any class method that is declared as a public function in quick-cache.inc.php or quick-cache-pro.inc.php using $GLOBALS['quick_cache']->any_public_method().

For example, if you wanted to clear the cache every time a post was saved or updated (i.e., when the save_post action is fired), you could add the following to your theme's functions.php file:

add_action( 'save_post', 'my_custom_purge_cache', 10, 1 );

function my_custom_purge_cache( ) {
    $GLOBALS['quick_cache']->clear_cache();
}

Clear page cache when Custom Post Type is saved

Using the save_post_{$post_type} hook, which is fired whenever that custom post type is created or updated (see docs), you can add something like the following to your theme's functions.php file, or to a MU-Plugin, to clear the cache for a given page whenever a post with that custom post type is saved:

add_action( 'save_post_my-custom-post-type', 'clear_cache_for_page_id_5', 10, 1 );

function clear_cache_for_page_id_5( ) {
	$GLOBALS['quick_cache']->auto_clear_post_cache(5);
}

You'll want to change 5 to the ID of the Page/Post whose cache you'd like to clear when that custom post type is saved, and you'll want to change my-custom-post-type to the actual name of your Custom Post Type.

Clear a specific page cache when saving any post

Using the save_post hook, which is fired whenever a post created or updated (see docs), you can add something like the following to your theme's functions.php file, or to a MU-Plugin, to clear the cache for a given page

add_action( 'save_post', 'clear_cache_for_page_id_5', 10, 1 );

function clear_cache_for_page_id_5( ) {
	$GLOBALS['quick_cache']->auto_clear_post_cache(5);
}

You'll want to change 5 to the ID of the Page/Post whose cache you'd like to clear.

Clear the cache for a Logged-In User (when caching for Logged-In Users is enabled)

To clear the cache for a specific user by passing the User ID, you can add the following to your theme's functions.php file, or to a MU-Plugin, to clear the cache for the user with User ID 25:

add_action( 'init', 'clear_user_cache_for_id_25', 10, 1 );

function clear_user_cache_for_id_25( ) {
	$GLOBALS['quick_cache']->auto_clear_user_cache(25);
}

You'll want to change 25 to the User ID whose cache you'd like to clear.

If you just want to clear the cache for the currently logged in user, you can use the following code instead (this uses get_current_user_id() to detect the User ID of the current user):

add_action( 'init', 'clear_current_user_cache', 10, 1 );

function clear_current_user_cache( ) {
	$GLOBALS['quick_cache']->auto_clear_user_cache_cur();
}