Categories
WordPress

Increasing the Max Results Returned from the WordPress REST API

Generally, the defaults connected with WordPress REST API responses are extremely reasonable. Situation in point, there aren’t many situations in which you would really should have more than 100 results in single API response. Pagination is supported, so generally loading more results is only a few making yet another request.

Sometimes You need to Break the guidelines

However, occasionally in which the defaults don’t work and you must do some personalization. One particular example that I came across was when attempting to populate data in the WordPress REST API right into a mobile application. We wanted to synchronize about 7,000 records. Implementing for 100 records at any given time would lead to 70 demands. Presuming each request required 1 second, it might take greater than a minute to sync up… no experience you would like for initial users of the mobile application. However, simply by bumping the utmost quantity of records to 500 we could reduce the amount of demands to 14 5x quicker than before.

But Break the guidelines Very carefully

Bear in mind, you ought to have a very good reason for growing the utmost quantity of results. Mistreating this ability can lead to both performance and security issues. The greater you place the worth, the greater processing power and memory is going to be needed to come back the end result. For additional popular sites, this might make you susceptible to denial and services information attacks.

Please, don’t allow unbounded queries. So don’t set the utmost to become 99999999. I’d reason that exceeding beyond 500 is most likely not smart.

Furthermore, don’t increate the utmost overall. Only boost the maximum for that specific publish type you have to change.

How you can Break the guidelines

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

add_filter( 'rest_post_collection_params', function ( $parameters, WP_Post_Type $post_type ) {

	if ( 'post' === $post_type->name && isset( $parameters['per_page'] ) ) {
		$parameters['per_page']['maximum'] = 200;
	}

	return $parameters;

}, 10, 2 );

By Ankit Panchal

I'm a WordPress consultant and Web developer. I like solving digital problems which help your business grow. I specialize in WordPress plugin development and frontend development and am available for hire.