Performance PHP Intermediate

Cache Expensive Queries in a Transient

Store the result of a slow query, like a "most popular posts" list, for 12 hours and clear it automatically when posts change.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 25 lines
/**
 * Example: the 5 most-commented posts, cached for 12 hours.
 * Usage: foreach ( nahnu_popular_posts() as $post ) { ... }
 */
function nahnu_popular_posts(): array {
	$cached = get_transient( 'nahnu_popular_posts' );
	if ( is_array( $cached ) ) {
		return array_filter( array_map( 'get_post', $cached ) );
	}

	$ids = get_posts( [
		'post_type'      => 'post',
		'posts_per_page' => 5,
		'orderby'        => 'comment_count',
		'fields'         => 'ids',
		'no_found_rows'  => true,
	] );

	set_transient( 'nahnu_popular_posts', $ids, 12 * HOUR_IN_SECONDS );
	return array_filter( array_map( 'get_post', $ids ) );
}

// Clear the cache when a post is published, updated or deleted.
add_action( 'save_post_post', fn () => delete_transient( 'nahnu_popular_posts' ) );
add_action( 'deleted_post', fn () => delete_transient( 'nahnu_popular_posts' ) );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Some queries are slow and their results rarely change: popular posts, featured products, counts across many posts. Running them on every page view wastes database time. Caching the result in a transient means the query runs once every few hours instead.

How it works

The function first looks for a stored result with get_transient(). If one exists, it returns those posts immediately. Otherwise it runs the query, stores only the post IDs (small and safe to cache) for 12 hours, and returns the posts.

Hooks on save_post_post and deleted_post delete the transient when posts change, so the list is never out of date for long.

Things to watch

  • Transients live in the options table unless you have a persistent object cache like Redis, in which case they’re stored there automatically.
  • Use a unique transient name for each cached query, and keep names under 172 characters.

How to test it

Call the function in a template and check Query Monitor: the query appears on the first load only. Save a post and the next load runs it again.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only