Fixing a Slow WordPress REST Endpoint Caused by get_post_meta in a Loop
How replacing a get_post_meta loop with one SQL query brought one custom WordPress REST endpoint from 850 ms to 42 ms.
· 3 min read · Erik Kubica
Headless WordPress sometimes has a poor reputation among frontend developers. They connect a Next.js or mobile client to a custom REST route, request a list of fifty catalog items, and the endpoint takes 850 ms to respond.
The natural reaction is "WordPress is slow, let's rewrite the backend in Go or Node."
After thirteen years of building and reviewing WordPress backends, I have found that in many cases the problem is not WordPress core, PHP, or the hosting. It is often a custom REST endpoint with an N+1 query loop, which is easy to write by accident.
The Loop
Here is the code pattern I found in a client's custom WooCommerce headless theme last month:
add_action('rest_api_init', function () {
register_rest_route('store/v1', '/featured', [
'methods' => 'GET',
'callback' => function () {
$posts = get_posts(['numberposts' => 50, 'post_type' => 'product']);
$data = [];
foreach ($posts as $post) {
$data[] = [
'id' => $post->ID,
'title' => $post->post_title,
'sku' => get_post_meta($post->ID, '_sku', true),
'price' => get_post_meta($post->ID, '_price', true),
'stock' => get_post_meta($post->ID, '_stock', true),
];
}
return rest_ensure_response($data);
},
'permission_callback' => '__return_true',
]);
});
Here is what this endpoint does behind the scenes:
1. One query to fetch fifty product rows from wp_posts.
2. Fifty iterations through the loop.
3. Three get_post_meta() calls per product.
That is 1 + (50 * 3) = 151 database queries per HTTP request. With eight custom fields it would be 401. When ten mobile clients request the feed at the same time, the database receives a few thousand queries in a second, MariaDB thread pools saturate, and latency climbs past 850 ms.
On this project, most of the latency came from the number of queries, not from PHP itself.
Reducing It to One Query
In this case I did not need to rewrite the backend in another language. I needed to reduce the number of queries.
Instead of running N+1 queries in PHP, you can prime the internal cache with WordPress's built-in update_meta_cache('post', $post_ids) before looping, or write a SQL join via $wpdb:
add_action('rest_api_init', function () {
register_rest_route('store/v1', '/products-fast', [
'methods' => 'GET',
'callback' => function () {
global $wpdb;
$sql = "SELECT p.ID, p.post_title,
MAX(CASE WHEN m.meta_key = '_sku' THEN m.meta_value END) AS sku,
MAX(CASE WHEN m.meta_key = '_price' THEN m.meta_value END) AS price,
MAX(CASE WHEN m.meta_key = '_stock' THEN m.meta_value END) AS stock
FROM {$wpdb->posts} p
LEFT JOIN {$wpdb->postmeta} m ON p.ID = m.post_id
AND m.meta_key IN ('_sku', '_price', '_stock')
WHERE p.post_type = 'product' AND p.post_status = 'publish'
GROUP BY p.ID, p.post_title
ORDER BY p.ID DESC
LIMIT 50";
$results = $wpdb->get_results($sql, ARRAY_A);
return rest_ensure_response($results);
},
'permission_callback' => '__return_true',
]);
});
With a single conditional aggregation query, the database returns all fifty products and their metadata in one roundtrip.
It also helps to have an index on (post_id, meta_key) in the wp_postmeta table. WordPress indexes post_id and meta_key separately by default, which can push MySQL into index merge operations when joining large datasets. With a composite index and the aggregation query, execution dropped to about 4 ms on that project.
The results on that project: - Database queries dropped from 151 to 1. - Endpoint latency went from 850 ms to 42 ms. - PHP memory stayed flat at around 18 MB while handling 600 req/s.
Priming the meta cache is usually the smaller and safer change, and the raw SQL version trades some readability for speed, so pick whichever fits the codebase. Before blaming a framework, it is worth looking at the database query log first. It was where I found the cause here.