Increasing the Max Results Returned from the WordPress REST API

Generally, the defaults associated with WordPress REST API responses are very reasonable. Case in point, there aren’t many situations where you would really need to get more than 100 results in a single API response. Pagination is supported, so in most cases loading more results is simply a matter of making an additional request.

Sometimes You Have to Break the Rules

However, there are occasions where the defaults don’t cut it and you need to do some customization. One such example that I ran into was when trying to populate data from the WordPress REST API into a mobile app. We needed to synchronize about 7,000 records. Making a request for 100 records at a time would result in 70 requests. Assuming each request took 1 second, it would take more than a minute to sync up… not an experience you want for initial users of your mobile app. However, by simply bumping the maximum number of records to 500 we were able to reduce the number of requests to 14; 5x faster than before.

But Break the Rules Cautiously

Keep in mind, you should have a good reason for increasing the maximum number of results. Abusing this ability can result in both performance and security issues. The higher you set the value, the more processing power and memory will be required to return the result. For more popular sites, this could open you up to denial of service attacks.

Please, don’t allow unbounded queries. So don’t set the maximum to be 99999999. I would argue that going above 500 is probably not smart.

Additionally, don’t increate the maximum across the board. Only increase the maximum for the specific post type you need to change.

How to Break the Rules

Here is an example of how you would increase the maximum items returned per response:

<?php

add_filter( 'rest_post_collection_params', function ( $params, WP_Post_Type $post_type ) {
	if ( 'post' === $post_type->name && isset( $params['per_page'] ) ) {
		$params['per_page']['maximum'] = 200;
	}

	return $params;
}, 10, 2 );

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.