---
url: /cookbook/cache-in-templates.md
description: >-
  Cache expensive element-template computations with WordPress transients and
  invalidate them through the wpce_save_node action.
---

# Cache Computationally Expensive Work in Templates&#x20;

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](https://developer.wordpress.org/apis/transients/) together with the [`wpce_save_node`](../hooks/actions/wpce-save-node.md) 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;
});
```
