I'm using WordPress rest API for developing my Android application. But I can not cache the response.
How can I add required headers to REST API response so that my app can save the response for offline reading?
I'm using WordPress rest API for developing my Android application. But I can not cache the response.
How can I add required headers to REST API response so that my app can save the response for offline reading?
Share Improve this question asked Aug 18, 2017 at 11:59 Amar IlindraAmar Ilindra 2051 gold badge3 silver badges8 bronze badges 5- what caching of any kind have to do with offline reading? if you need to store a response in your app, just store it. – Mark Kaplun Commented Aug 18, 2017 at 12:24
- I'm using Volley which will automatically cache the response. But I it is not caching only WP rest API response. Do I need to add any headers to say volley to cache them? – Amar Ilindra Commented Aug 18, 2017 at 12:27
- no idea what is volley ;) just doesn't sound right that caching info in an app depends on headers sent by the server. You can write a plugin to set headers on specific request, just sounds weird. – Mark Kaplun Commented Aug 18, 2017 at 12:31
- Caching in the application depends on the headers of response we received. Read this: devcenter.heroku/articles/… I'm not a server guy and I don't know the exact terms to describe it. – Amar Ilindra Commented Aug 18, 2017 at 12:33
- you can use this plugin wordpress/plugins/wp-rest-cache – user8889 Commented Aug 2, 2021 at 5:35
1 Answer
Reset to default 7You should create a new instance from WP_REST_Response
to set the Cache-Control
value.
<?php
register_rest_route('wp/v2', '/your_endpoint', array(
'methods' => 'GET',
'callback' => 'function_callback',
));
function function_callback($data) {
$response = array(
1,2,3,4,5,6,7,8
);
$result = new WP_REST_Response($response, 200);
// Set headers.
$result->set_headers(array('Cache-Control' => 'max-age=3600'));
return $result;
}
Click here to get more info about directives.