Replacing a WP_Query loop with one cached query

The homepage ran a fresh WP_Query for every section. Here is the small helper that replaced them.

The shape of the old code

We started by adding types at the edges: return types on the functions we called most, and a static analysis baseline so new code could not make things worse.

function quietloop_recent_ids( $number = 10 ) {
	$key = 'recent_ids_' . $number;
	$ids = wp_cache_get( $key, 'quietloop' );

	if ( false === $ids ) {
		$ids = get_posts(
			array(
				'fields'         => 'ids',
				'posts_per_page' => $number,
				'no_found_rows'  => true,
			)
		);
		wp_cache_set( $key, $ids, 'quietloop', HOUR_IN_SECONDS );
	}

	return $ids;
}

Hooks are a contract. Before we moved any callback we listed every add_action and add_filter call that depended on it and wrote a test for the ones that mattered. The snippet above is the whole thing; the version in our repository only adds tests.

What changed for the team

  • Add a static analysis baseline on day one
  • Type the boundaries before the internals
  • Keep hook names stable while moving callbacks
  • Delete dead code in its own commit

8 comments on “Replacing a WP_Query loop with one cached query”

    1. Elin Sørensen

      Thanks for reading! We tested on a mid-range Android phone as well, and the results were close to the throttled runs.

  1. Nadia Petrova

    I shared this with my team. The list near the end is going straight into our onboarding doc.

  2. Kwame Asante

    Clear and practical, thank you. One question: how long did the whole change take from start to finish?

  3. Grace Whitmore

    Great post. Did you measure this on a real phone as well, or only with throttling in the browser?

  4. Aiko Tanaka

    I disagree slightly on the tooling choice, but the reasoning is solid and well explained.

  5. Clara Lindqvist

    Bookmarked. The part about writing things down before changing anything is underrated.

Leave a comment

Your email address will not be published. Required fields are marked *