Cache Computationally Expensive Work in Templates v3.20
There may be situations where you'd want to do heavy work while generating an element's template once, and then cache the result for future use (e.g. analyzing or modifying child content using DOMDocument).
This can be done comfortably using WordPress' Transients API together with the wpce_save_node action.
php
// Delete cached value when `example` element is saved
add_action('wpce_save_node', function ($node) {
if ($node->id === 'example') {
delete_transient("wpce-example-{$element->guid}");
}
});
// Render `example` element
add_action('wpce_render_example', function ($wpce, $element) {
$cache_key = "wpce-example-{$element->guid}";
$refined_content = get_transient($cache_key);
if ($refined_content === false) {
$raw_content = $wpce->get_inner_html();
$refined_content = /* Do something expensive with $raw_content */;
// Cache for a week
set_transient($cache_key, $refined_content, 60 * 60 * 24 * 7);
}
return <<<HTML
<div class="example">
{$refined_content}
</div>
HTML;
});