Store the result of a slow query, like a "most popular posts" list, for 12 hours and clear it automatically when posts change.
/**
* 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' ) );
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.
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.
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.