5

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 : rest_request_from_url but it never seems to fire.

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

Is there nothing like this request reference 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.

2 Answers 2

4

I think I found answer to your question, it is: rest_{$this->post_type}_query filter hook. With this hook you are able to directly edit internal WP_Query parameter.

For example, if you'd like to internally sort Posts by post_title by default, then you'd have to write something like this:

function order_rest_post_by_post_title($args, $request) {
  $args['orderby'] = 'post_title';
  $args['order'] = 'DESC';

  return $args;
}
add_filter('rest_post_query', 'order_rest_post_by_post_title', 10, 2);

For more info please follow this link.

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);
1
  • 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? Commented Nov 27, 2017 at 3:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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