With WordPress API, it is very convenient and easy to build web and mobile apps powered by WordPress. One limitation that you may run into is that the post type endpoints have a limit of 100 results. If you ask for more than 100 results, will return following error:
{ | |
"code": "rest_invalid_param", | |
"message": "Invalid parameter(s): per_page", | |
"data": { | |
"status": 400, | |
"params": { | |
"per_page": "per_page must be between 1 (inclusive) and 100 (inclusive)" | |
} | |
} | |
} |
In some cases, you may want more than 100 results. In my case, I was building a web app using Angular and it needed to load all the customers on the page. Since there were only 150 or so customers and I knew that they would never cross 500 , I wanted to load all of them in one request and display later using data tables.
I could not find any resources that allowed me to override number of results. A bit of research lead me to rest_{$this->post_type}_query
hook. It executes only for the post type we mention, so that’s perfect for our use case.
In my case, here’s the code I ended up with:
<?php | |
add_action( 'rest_customer_query', 'customer_override_per_page' ); | |
/* | |
* params is the query array passed to WP_Query | |
*/ | |
function customer_override_per_page( $params ) { | |
if ( isset( $params ) AND isset( $params[ 'posts_per_page' ] ) ) { | |
$params[ 'posts_per_page' ] = PHP_INT_MAX; | |
} | |
return $params; | |
} |
The post type in my case is customer. So the hook becomes rest_customer_query
. $params
is just an array passed to our function that’s used for WP_Query
. You can modify it to alter results. I am setting $params['posts_per_page']
to PHP constant PHP_INT_MAX
to get all the results.
Have any better approach in mind? Do let me know via comments.
Thank you, this is exactly what I was looking for!
Guys i having same problem. can you show
“In my case, here’s the code I ended up with” where i need to update this code ?
I’d also like to know
Hi,
not working in wordpress 5.1… any solution?
Sorry 🙂 my mistake
I needed rest_{$taxonomy}_collection_params hook 🙂 now work..
Hello,
There is woocommerce on my website. I have to make per_page 300 to pull all of the categories.
But I don’t know how. I included this code in wp-includes / funcitions.php but it didn’t work.
I installed it in funcitions.php in the theme folder, it didn’t work again.
Link path for the category;
https://www.pratikbakkal.com/wp-json/wc/v2/products/categories?per_page=100&consumer_key=ck_……
Exactly the same question! Where should I put this code? I need to load all categories in single call.