Skip to content

Commit

Permalink
Don't cache non-200 header status responses.
Browse files Browse the repository at this point in the history
  • Loading branch information
Austin Passy committed Jan 25, 2018
1 parent b1514f7 commit 3fdd76c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
19 changes: 17 additions & 2 deletions class-wp-rest-cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* Description: Enable caching for WordPress REST API and increase speed of your application
* Author: Aires Gonçalves
* Author URI: http://github.com/airesvsg
* Version: 2.0.2
* Version: 2.0.3
* Plugin URI: https://github.com/airesvsg/wp-rest-api-cache
* License: GPL2+
*/
Expand All @@ -27,7 +27,7 @@ class WP_REST_Cache {
const CACHE_HEADER_DELETE = 'X-WP-API-Cache-Delete';
const CACHE_REFRESH = 'rest_cache_refresh';

const VERSION = '2.0.2';
const VERSION = '2.0.3';

/**
* Initiate the class.
Expand Down Expand Up @@ -153,6 +153,21 @@ public static function pre_dispatch( $result, WP_REST_Server $server, WP_REST_Re
*/
public static function post_dispatch( WP_REST_Response $response, WP_REST_Server $server, WP_REST_Request $request ) {
$request_uri = self::get_request_uri();
$allowed_cache_status = apply_filters( 'allowed_rest_cache_status', array( WP_Http::OK ) );
if ( ! in_array( $response->get_status(), $allowed_cache_status, true ) ) {
$key = self::get_cache_key( $request_uri, $server, $request );
$server->send_header(
self::CACHE_HEADER,
esc_attr_x(
'skipped',
'When rest_cache is skipped. This is the header value.',
'wp-rest-api-cache'
)
);
add_action( 'shutdown', function() use ( $key ) {
call_user_func( array( __CLASS__, 'delete_cache_by_key' ), $key );
} );
}
self::maybe_send_headers( $request_uri, $server, $request, $response );

return $response;
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ Filters
| rest_cache_show_admin | boolean **$show** |
| rest_cache_show_admin_menu | boolean **$show** |
| rest_cache_show_admin_bar_menu | boolean **$show** |
| allowed_rest_cache_status | array **$status** HTTP Header statuses (defaults to `array( 200 )` |

How to use filters
----
Expand Down

0 comments on commit 3fdd76c

Please sign in to comment.