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.
2 s
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.