Avoid N+1 queries in WordPress: prime the meta and term caches
The N+1 problem: one query fetches a list of N items, and then every item in a loop makes one more query for its related data. With 50 posts that is 51 queries, with 200 posts it is 201. In WordPress it usually happens with get_post_meta(), get_the_terms() or get_user_meta() called inside a loop over posts or users that were loaded without their caches.
Problem: A custom admin page shows 50 events with the meta field _event_date and the terms of event_category, and Query Monitor shows a separate query for every post.
Solution: Load the related data for all posts at once before the loop. WP_Query does it by default; when you only have post IDs, prime the caches yourself with _prime_post_caches() or update_meta_cache().
When WordPress already batches the queries
A normal WP_Query (and get_posts(), which uses it) loads the meta and the terms of all found posts in two extra queries. Inside the loop get_post_meta() and get_the_terms() read from the cache:
<?php
$query = new WP_Query( array(
'post_type' => 'event',
'posts_per_page' => 50,
'no_found_rows' => true, // no pagination, so skip the COUNT query
// 'update_post_meta_cache' => true, // default
// 'update_post_term_cache' => true, // default
) );
while ( $query->have_posts() ) {
$query->the_post();
$date = get_post_meta( get_the_ID(), '_event_date', true ); // from cache
$terms = get_the_terms( get_the_ID(), 'event_category' ); // from cache
}
wp_reset_postdata();
// About 3 queries in total, whatever the number of posts
If the loop does not use meta or terms, turn the priming off with 'update_post_meta_cache' => false and 'update_post_term_cache' => false to save those two queries.
Where N+1 really appears
The problem starts when the list of posts comes without its caches: 'fields' => 'ids', a custom $wpdb query, IDs stored in a meta field or an option. Then every get_post_meta() and get_the_terms() in the loop is a separate query:
<?php
// BAD: 1 + 50 + 50 queries
$ids = get_posts( array( 'post_type' => 'event', 'posts_per_page' => 50, 'fields' => 'ids' ) );
foreach ( $ids as $id ) {
$date = get_post_meta( $id, '_event_date', true );
$terms = get_the_terms( $id, 'event_category' );
}
Prime the caches for the whole list before the loop:
<?php
// GOOD: posts, their terms and their meta in a few queries
_prime_post_caches( $ids, true, true ); // IDs, update term cache, update meta cache
foreach ( $ids as $id ) {
$date = get_post_meta( $id, '_event_date', true ); // from cache
$terms = get_the_terms( $id, 'event_category' ); // from cache
}
If you need only the meta (not the post objects), update_meta_cache() is enough. It works for users and terms too:
<?php
$user_ids = array( 1, 3, 7, 12 );
update_meta_cache( 'user', $user_ids ); // all meta of these users in one query
foreach ( $user_ids as $user_id ) {
$company = get_user_meta( $user_id, 'company', true ); // from cache
}
One meta key for many posts
When you need a single field for hundreds of posts, one direct query is lighter than loading all their meta:
<?php
global $wpdb;
$ids_in = implode( ',', array_map( 'absint', $ids ) );
$rows = $wpdb->get_results(
"SELECT post_id, meta_value FROM {$wpdb->postmeta}
WHERE meta_key = '_event_date' AND post_id IN ($ids_in)"
);
$date_map = wp_list_pluck( $rows, 'meta_value', 'post_id' ); // post_id => date
The IDs go through absint() before they are put into the SQL, so the list is safe without prepare().
NOTE: To find N+1 problems, install Query Monitor: it groups the queries by the function that called them, and a function with 50 identical queries is easy to spot. With a persistent object cache (Redis, Memcached) the repeated queries go to the cache instead of MySQL, but the first uncached page load still makes all of them.