Repository navigation
Hook examples
These are short worked examples of the hooks and helper functions in Ace Redis Cache 0.10.6. I use the plugin on my own sites, and most of these come from code I run there, rewritten with generic names: the shape of the code is real and the names are not. Every example can be pasted into a small plugin or mu-plugin, and each ends with the response header or command that shows it working.
To read the response header, request the page as a signed-out visitor, for example curl -sI https://example.com/ | grep -i x-aceredis. A page served from the cache says X-AceRedisCache: HIT. Anything else carries one reason, such as MISS; reason=empty_main or BYPASS; reason=excluded_path.
- Refresh a list of known pages after an import
- Mark the whole site stale after a deploy
- Stop an import marking the whole site stale
- Purge one URL from your own code
- Opt a custom route into the page cache
- Refuse to store a page that is missing something
- Give each kind of page its own lifetime
- Exclude URLs from the page cache
- Add a part to the page cache key
- Keep a block live on a cached page
- Let crawlers bypass the cache on named paths
- Make an HTML rewrite survive a cache hit
- A block cache profile with its own lifetime
- Cache a slow wp-admin query
- Keep your own object cache group in Redis
One of my sites lists events and imports new ones several times an hour. Each import changed a handful of pages (the home page and the listing pages), but I was marking every stored page stale each time, so the cache never got back to fresh. aceredis_refresh_urls() refreshes only the pages you name: each stored copy, desktop and mobile, is kept and served while a new one is rendered in the background.
/**
* Refresh the pages that list events. Call it at the end of an import run.
*
* @param bool $prime False only marks the pages stale; they refresh when next visited.
* @return string What was done: 'refresh', 'soft' or 'none'.
*/
function mysite_refresh_event_listings( $prime = true ) {
$urls = array(
home_url( '/' ),
home_url( '/events/' ),
home_url( '/events/this-weekend/' ),
);
if ( function_exists( 'aceredis_refresh_urls' ) && false !== aceredis_refresh_urls( $urls, (bool) $prime ) ) {
return 'refresh';
}
// The page cache is not running here, or the plugin is older than 0.10.1.
if ( function_exists( 'aceredis_soft_purge_page_cache' ) && aceredis_soft_purge_page_cache() ) {
return 'soft';
}
return 'none';
}
add_action( 'mysite_import_finished', 'mysite_refresh_event_listings' );aceredis_refresh_urls() returns the number of refreshes it queued, or false when the page cache is off. Request one of the listed pages straight after an import: it should still answer X-AceRedisCache: HIT (the old copy), and a second request a few seconds later should show the new content, still as a HIT. A page that is not in the list keeps its copy untouched. wp aceredis warm https://example.com/events/ does the same job by hand.
When I deploy a release that changes how every page renders, every stored page is out of date. Deleting them all sends every visitor and crawler to a cold render at the same moment. aceredis_soft_purge_page_cache() marks every stored page stale instead: each one is still served while the background refresher renders its replacement.
/**
* Mark every stored page stale. Run it from the deploy, for example with
* `wp eval 'do_action( "mysite_deployed" );'`.
*/
function mysite_mark_pages_stale() {
// True skips the coalescing window: a deploy should not wait.
if ( function_exists( 'aceredis_soft_purge_page_cache' ) && aceredis_soft_purge_page_cache( true ) ) {
return;
}
// Soft purging is not possible here, so fall back to a plain flush.
wp_cache_flush();
}
add_action( 'mysite_deployed', 'mysite_mark_pages_stale' );
// Routine callers (an import, a settings save) leave the argument out. Their calls
// are gathered into one trailing purge; this sets how far apart purges may be.
add_filter(
'aceredis_soft_purge_min_interval',
function () {
return 10 * MINUTE_IN_SECONDS;
}
);Straight after the deploy, pages answered before WordPress starts say X-AceRedisCache: HIT (advcache, stale): the old copy was served and a refresh is queued. A later request for the same page says HIT without stale. No page should say MISS only because of the deploy. wp aceredis status confirms the cache is on and Redis answers.
With the wider purge switched on, saving any post marks the rest of the site stale. That is right for a page or a menu, and wrong for an import that saves hundreds of items a day, which is what one of my sites does. The plugin already recaches the saved post's own page, the home page, its archive and its term pages, so the import only needs to add the listings the plugin cannot know about.
// After the plugin's own default at priority 10.
add_filter(
'aceredis_broad_page_cache_purge_on_post_update',
function ( $broad, $post_id = 0, $post = null ) {
$type = $post instanceof WP_Post ? $post->post_type : get_post_type( (int) $post_id );
return in_array( $type, array( 'event', 'venue' ), true ) ? false : $broad;
},
20,
3
);
// The extra pages to recache when an event is saved.
add_filter(
'aceredis_recache_related_urls',
function ( $urls, $post = null ) {
if ( $post instanceof WP_Post && 'event' === $post->post_type ) {
$urls[] = home_url( '/events/' );
$urls[] = home_url( '/events/this-weekend/' );
}
return array_values( array_unique( array_filter( (array) $urls ) ) );
},
10,
2
);Save an event, then request an unrelated page (an article, say): it should say HIT, not HIT (advcache, stale). Request /events/ a few seconds later: it should be a HIT that already shows the change. Saving a page or a menu should still mark the other pages stale.
On a news site I work on, a setting changes one known page, and a small public REST response is kept in the page cache. Saving the setting does not save a post, so nothing tells the cache. Firing the aceredis_cache_purge_url action deletes the stored copies of that one address and leaves everything else alone.
/**
* Drop the stored copy of the pages that show the featured article.
*
* @param int $post_id The article that was featured or unfeatured.
*/
function mysite_purge_featured( $post_id ) {
$urls = array(
get_permalink( $post_id ),
home_url( '/' ),
home_url( '/wp-json/mysite/v1/featured' ),
);
foreach ( array_filter( $urls ) as $url ) {
// An action, so nothing breaks while the plugin is switched off.
do_action( 'aceredis_cache_purge_url', $url );
}
}
add_action( 'mysite_featured_changed', 'mysite_purge_featured' );The first request for the address after the purge should not say HIT; the second should. wp aceredis purge https://example.com/ does the same from the command line, which is a quick way to prove that a stale page is a caching matter and not a rendering one.
The page cache starts on WordPress's template_include filter. One of my plugins renders its routes itself and exits in template_redirect, so it never reached that filter and its pages were rendered in full for every visitor. Firing aceredis_start_page_cache just before output starts opts that response in.
/**
* Page cache our own public, read-only routes. Anything that changes by the
* minute, or is personal to the visitor, is left out on purpose.
*/
function mysite_cache_own_routes() {
$cacheable = array( 'mysite_map', 'mysite_directory', 'mysite_archive' );
foreach ( $cacheable as $query_var ) {
if ( get_query_var( $query_var ) ) {
do_action( 'aceredis_start_page_cache' );
return;
}
}
}
// Before the callback that renders the route and exits.
add_action( 'template_redirect', 'mysite_cache_own_routes', -100 );Request the route twice as a signed-out visitor. The second response should say X-AceRedisCache: HIT. A signed-in visitor still gets BYPASS; reason=logged_in, and a response that is not a 200 is never stored (MISS; reason=status_not_200). If the header is missing entirely, the action fired after output had already started, or the request is one the page cache never handles (not a GET, or an excluded path).
On my events site a single event page sits in the cache for up to a week. If one render came out half finished (an upstream call timed out, a template part failed), that broken copy would be served for the whole week. The aceredis_page_store_block_reason filter lets the site insist on what a page must contain before it is kept.
add_filter(
'aceredis_page_store_block_reason',
function ( $reason, $content ) {
// Leave a reason from the plugin, or from another callback, alone.
if ( null !== $reason || ! is_singular( 'event' ) ) {
return $reason;
}
if ( false === strpos( $content, '<h1' ) ) {
return 'event_without_headline';
}
if ( false === strpos( $content, '"@type":"Event"' ) ) {
return 'event_without_schema';
}
return null;
},
10,
2
);A good page is stored as usual: MISS on the first view, HIT afterwards. A page that fails a test says X-AceRedisCache: MISS; reason=event_without_headline on every request until it renders properly, so the reason you return is what you will see in the header. Keep it short, lower case and without spaces. Return null to allow the page.
I found one lifetime for every URL a poor fit. A single product or event changes only when it is edited (and is purged then), so it can stay for a day or more, while a listing moves as items are added and wants a fresh copy sooner. Filtered views, with a query string, are many and cheap, so they should be short. aceredis_page_ttl sets how long a page is fresh, and aceredis_page_grace sets how long a stale copy may still be served while one background refresh runs.
add_filter(
'aceredis_page_ttl',
function ( $ttl, $uri ) {
if ( false !== strpos( (string) $uri, '?' ) ) {
return 15 * MINUTE_IN_SECONDS;
}
if ( is_singular( array( 'product', 'page', 'post' ) ) ) {
return DAY_IN_SECONDS;
}
if ( is_front_page() || is_home() || is_post_type_archive() || is_tax() || is_category() || is_tag() ) {
return 6 * HOUR_IN_SECONDS;
}
return $ttl;
},
10,
2
);
add_filter(
'aceredis_page_grace',
function ( $grace, $uri ) {
// Filtered views are cheap to render, so they are not worth keeping stale.
if ( false !== strpos( (string) $uri, '?' ) ) {
return 0;
}
return max( (int) $grace, DAY_IN_SECONDS );
},
10,
2
);On a response rendered by WordPress, X-AceRedisCache-Orig-TTL shows the lifetime the page was stored with and X-AceRedisCache-TTL-Remaining shows what is left. Compare a single page with a listing: the numbers should differ as the filter says. Both filters run while the page is being rendered, so conditional tags such as is_singular() work in them.
One of my sites has a registration page that carries a signed, short-lived token in its form. A stored copy would hand every visitor the same expired token. aceredis_cache_excluded_urls keeps WordPress from storing or serving the page, and aceredis_early_bypass_paths tells the drop-in, which answers before WordPress starts and cannot ask it, never to serve those paths either.
/**
* Paths that must be rendered for every visitor.
*
* @return string[]
*/
function mysite_uncached_paths() {
return array( '/register/', '/submit-an-event/' );
}
// Matched anywhere in the request URI, so '/register/' also covers '/register/?step=2'.
add_filter(
'aceredis_cache_excluded_urls',
function ( $patterns ) {
return array_merge( (array) $patterns, mysite_uncached_paths() );
}
);
// Path prefixes the drop-in must pass on to WordPress.
add_filter(
'aceredis_early_bypass_paths',
function ( $paths ) {
return array_merge( (array) $paths, mysite_uncached_paths() );
}
);Every request for the path should say X-AceRedisCache: BYPASS; reason=excluded_path, however many times it is asked for. If a copy was stored before the exclusion was added, remove it once with wp aceredis purge https://example.com/register/. WooCommerce's basket, checkout and account pages are excluded already and need no entry.
A news site I work on has a display setting that changes the markup of every article. After I changed the setting, stored pages went on showing the old markup until each one expired. Adding the setting's state to the page cache key means a change is a new key: the old copies are simply never asked for again.
add_filter(
'aceredis_cache_page_cache_key_parts',
function ( $key_parts ) {
if ( ! is_array( $key_parts ) ) {
return $key_parts;
}
$settings = (array) get_option( 'mysite_display', array() );
$key_parts[] = 'mysite-hl-' . (int) ! empty( $settings['highlight_updates'] );
return $key_parts;
}
);Request a page until it is a HIT, change the setting, and request it again: the first response should not be a HIT and should show the new markup, and the one after should be a HIT. Change the setting back and the earlier copy is found again. Only add values that are the same for every visitor and that are known early in the request. A value that differs per visitor makes one stored copy per visitor.
A news site I work on shows a live scores ticker in its header. The page around it can be cached for hours, but the ticker must not be. Excluding the page would lose the cache for every page on the site, because the ticker is on all of them.
This one is mostly a setting. Under Block Exclusions, list the block (mysite/live-scores, or a pattern such as mysite/live-*), and tick "Treat excluded blocks as dynamic". The block is then stored as a placeholder and rendered when the page is served, with a short-lived copy shared between visitors. Two filters adjust it from code:
// Add a block from code, next to any listed in the setting. The setting must be
// ticked. From 0.10.6 it does not have to list a block for this filter to run.
add_filter(
'aceredis_dynamic_block_patterns',
function ( $patterns ) {
$patterns[] = 'mysite/live-prices';
return array_values( array_unique( $patterns ) );
}
);
// How long an older copy of a live block may stand in while a new one is
// rendered in the background. The default is between five minutes and an hour.
add_filter(
'aceredis_dynamic_stale_ttl',
function ( $seconds, $block_name ) {
return 'mysite/live-scores' === $block_name ? 2 * MINUTE_IN_SECONDS : $seconds;
},
10,
2
);The page still says X-AceRedisCache: HIT. A response that WordPress filled in also carries X-AceRedisCache-Dynamic: on and X-AceRedisCache-Dynamic-Count with the number of live blocks on the page. Load the page twice a minute apart: the ticker should have moved and the rest of the page should not have been rendered again. The block must render the same for every visitor, since its short-lived copy is shared.
A site renders one section differently for search crawlers than for visitors, for example a fully expanded version of pages that visitors load in stages. A stored visitor copy must not be handed to the crawler, and the crawler's copy must not be stored for visitors. aceredis_crawler_bypass names the user agents and the path prefixes where they are always served live. None of my sites uses this filter at present, so the example follows the plugin's own source.
add_filter(
'aceredis_crawler_bypass',
function ( $rule ) {
// The body of a regular expression, matched without regard to case.
$rule['agents'] = 'Googlebot|bingbot|DuckDuckBot';
// Path prefixes. '/' on its own is ignored: never the whole site.
$rule['paths'] = array( '/directory/', '/guides/' );
return $rule;
}
);curl -sI -A "Googlebot" https://example.com/directory/ should say X-AceRedisCache: BYPASS; reason=crawler. The same request with an ordinary browser user agent should say HIT, and so should the crawler on a path that is not listed. The rule is empty by default, so nothing changes until both the agents and at least one path are set.
One of my sites belongs to a family of sites and shares its navigation data with the main one, so some links in the finished page point at pages that exist only on the main site. I used to rewrite those links in an output buffer of my own. That buffer sat outside the one the page cache stores from, so the stored copy held the links as they were before the rewrite and every cache hit lost it. From WordPress 6.9, WordPress owns the whole response buffer and passes the finished page through wp_template_enhancement_output_buffer; the plugin stores the page from that filter at the default priority, so a rewrite at an earlier priority is stored with the page.
add_filter(
'wp_template_enhancement_output_buffer',
function ( $html ) {
$main = 'https://www.example.com';
$home = untrailingslashit( home_url() );
// Send links to the help pages across to the main site.
$out = preg_replace(
'#href="(?:' . preg_quote( $home, '#' ) . ')?(/help(?:/[^"\#?]*)?)(["\#?])#',
'href="' . $main . '$1$2',
(string) $html
);
// preg_replace() returns null on failure: keep the page as it was.
return null === $out ? $html : $out;
},
5 // Before the page cache stores the page at priority 10.
);Request a page until it says X-AceRedisCache: HIT, then look for the rewritten link in that response body, for example curl -s https://example.com/ | grep -c 'https://www.example.com/help'. It must be there on the hit, not only on the first render. This is a WordPress filter, so it needs no function_exists() check and runs whether or not the plugin is active.
My events site has one heavy block that draws its listings, and it appears on the home page and on every archive. It was the slowest part of each uncached render. A block cache profile stores the block's output on its own, with a lifetime and a key that suit it, so a page that has to be rendered again does not have to render the block again.
add_filter(
'aceredis_block_cache_profiles',
function ( $profiles ) {
$profiles['mysite_listings'] = array(
'label' => 'Event listings',
'setting' => 'block_cache_custom', // Follows the "Custom blocks" switch.
'blocks' => array( 'mysite/event-list' ),
'dep_types' => null,
'role_safe' => false, // Signed-in visitors get a live render.
'bump_on_update' => true, // Any publish or update retires the profile.
'vary_page' => true, // The block reads the page it is on.
'vary' => static function () {
return current_time( 'Y-m-d' ); // Upcoming and past split by today's date.
},
'ttl' => 15 * MINUTE_IN_SECONDS,
);
return $profiles;
}
);
// Only cache the plain view: any query argument that is not tracking means a live render.
add_filter(
'aceredis_block_cache_cacheable',
function ( $ok, $block, $profile ) {
if ( 'mysite_listings' !== $profile || ! $ok ) {
return $ok;
}
foreach ( array_keys( $_GET ) as $arg ) { // phpcs:ignore WordPress.Security.NonceVerification
if ( ! preg_match( '/^(utm_[a-z]+|fbclid|gclid)$/', (string) $arg ) ) {
return false;
}
}
return true;
},
10,
3
);wp aceredis block-cache stats lists the profile with its hits and misses once the block has been rendered a few times. Hits should far outnumber misses on a busy page. After publishing an event the next render is a miss (the profile was retired) and those after it are hits again. wp aceredis block-cache flush empties the block cache if a stored block is wrong.
One of my plugins has a report screen in wp-admin that shows counts, each of which scans a whole meta table. The screen took seconds to load and the counts change only when the report's own data is written. aceredis_admin_cache_remember() keeps the result, and aceredis_admin_cache_bump() drops it wherever the data changes, so no stale number is shown.
/**
* A count that is slow to work out, kept while nothing it depends on changes.
*
* @return int
*/
function mysite_report_flagged_count() {
$compute = function () {
global $wpdb;
return (int) $wpdb->get_var(
$wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = %s", '_mysite_flagged' )
);
};
if ( ! function_exists( 'aceredis_admin_cache_remember' ) ) {
return $compute();
}
// The key is prefixed with our slug; the hour only bounds drift from outside writes.
return (int) aceredis_admin_cache_remember( 'mysite_report:flagged', $compute, array( 'mysite_report' ), HOUR_IN_SECONDS );
}
/** Call this wherever the flag is written or removed. */
function mysite_report_forget() {
if ( function_exists( 'aceredis_admin_cache_bump' ) ) {
aceredis_admin_cache_bump( 'mysite_report' );
}
}
add_action( 'mysite_flag_changed', 'mysite_report_forget' );Turn on the "wp-admin query cache" setting; with it off the helper runs the callback every time, so the code is safe either way. Load the screen twice and compare the query count or the load time: the second load should not run the count. Change the data and reload: the number should be right at once, which shows the bump works. A callback that returns null is not stored.
The object cache keeps a fixed list of groups in Redis. A group it does not know is held for the length of the request only, so when I stored rendered fragments in a group of my own with wp_cache_set() they were gone on the next request. Since 0.10.5, aceredis_add_persistent_groups() adds a group to the list.
// In a plugin or mu-plugin, at load time: the object cache is already running.
if ( function_exists( 'aceredis_add_persistent_groups' ) ) {
aceredis_add_persistent_groups( array( 'mysite_fragments' ) );
}
// Only for groups whose writes must reach Redis from signed-in and editing
// requests too, such as a fragment an editor has just changed.
if ( function_exists( 'aceredis_add_write_through_groups' ) ) {
aceredis_add_write_through_groups( array( 'mysite_fragments' ) );
}
/**
* A fragment kept between requests.
*
* @return string
*/
function mysite_sidebar_fragment() {
$html = wp_cache_get( 'sidebar', 'mysite_fragments' );
if ( false === $html ) {
$html = mysite_render_sidebar();
wp_cache_set( 'sidebar', $html, 'mysite_fragments', HOUR_IN_SECONDS );
}
return $html;
}Both functions exist only while the plugin's object-cache.php is the object cache, so keep the function_exists() checks. wp aceredis dropin status object confirms the drop-in is installed and current. Then set a value in one request and read it in another, for example wp eval 'var_dump( wp_cache_get( "sidebar", "mysite_fragments" ) );' after loading a page that calls the function: it should print the stored HTML, not false.
If I already run Ace Popular Posts, I can use its existing ranking when ARC builds the warmer list. This example gives priority only to URLs already eligible for warming. The homepage keeps its first slot. Posts with no recorded views keep their normal place. The warmer keeps its normal batch size, load limit and missing-page check.
add_filter( 'aceredis_warm_urls', static function ( $urls ) {
if ( ! function_exists( 'ace_get_popular_posts' ) || ! $urls ) {
return $urls;
}
$eligible = array_fill_keys( $urls, true );
$ranked = array( reset( $urls ) );
foreach ( (array) ace_get_popular_posts( 20, 7 ) as $post ) {
if ( empty( $post->post_id ) || empty( $post->views ) ) {
continue;
}
$url = get_permalink( $post->post_id );
if ( $url && isset( $eligible[ $url ] ) ) {
$ranked[] = $url;
}
}
return array_values( array_unique( array_merge( $ranked, $urls ) ) );
} );ARC reads the ranked list during warming. The example adds no visitor identifiers, client-side requests or per-hit Redis writes. I compare the share of public requests that hit Redis and the number of background renders over similar traffic periods before deciding whether to keep the change.
Ace Redis Cache: a page cache and object cache for WordPress, backed by Redis or Valkey. Written and maintained by Shane Rounce at AceMedia. Website · Repository · Issues · GPLv2 or later
Setting up
The caches
Your stack
Reference
Help
