2

I am building an application using WordPress Rest API.

I want to make simple calls to the API, such as just /wp-json/wp/v2/posts and let the backend have a systematic way how to handle this and serve /wp-json/wp/v2/posts?per_page=7 under the hood instead.

Basically, how can I override the defaults for the Rest API responses without specifying them in the query string?

Again, I don't want to pass parameters in the query string. I need simple query strings and standardized responses.

This: WordPress Docs - Modifying Responses doesn't seem to cover my use case, it is to add fields and the like, which is not what I want to do. I'm looking for a way to hook into the request and alter it before returning a response.

So something a little before this hook: Rest API Hook When Post Is Requested perhaps?

I gather that the above hook has already gotten ready to serve the response, I want to hook in before that to change the request headers.

EDIT:

The closest filter I have found is : this one but it never seems to fire.

Furthermore, rest_pre_dispatch is filtering the response, not the request.

Is there nothing like this for the Rest API?

If so, how do I alter the response without slowing down my server, since it will fetch 10 posts by default before I chop it down to however many I actually want.

0

To define default values, you can use the filter rest_{$post_type}_collection_params like that :

$post_type = "post";

add_filter("rest_{$post_type}_collection_params", function ($query_params, $post_type) {

    $query_params["per_page"]["default"] = 7;

    return $query_params;

}, 10, 2);
  • Do you think it would be better, if I don't want default routes anyway, to just disable the default and return my own custom endpoints that return exactly what I want? – Summer Developer Nov 27 '17 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.