Created
May 3, 2018 14:17
-
-
Save GeekPress/34e6ee60b777f85fa4d21970bbe4a7fe to your computer and use it in GitHub Desktop.
admin-ajax.php Request Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$cached_ajax_requests = array( | |
'your-action-here', | |
); | |
$cached_ajax_expiration_time = 7 * DAY_IN_SECONDS; | |
if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_REQUEST['action'] ) && in_array( $_REQUEST['action'], $cached_ajax_requests ) ) { | |
$request_id = get_rocket_request_uniqid_171286(); | |
$data = get_transient( 'rocket_get_ajax_cache_' . $request_id ); | |
if ( ! empty( $data ) ) { | |
if ( rocket_is_json_171286( $data ) ) { | |
$data = json_decode( $data ); | |
wp_send_json( $data ); | |
} | |
echo $data; | |
die(); | |
} | |
ob_start(); | |
add_action( 'shutdown', function() { | |
$request_id = get_rocket_request_uniqid_171286(); | |
set_transient( 'rocket_get_ajax_cache_' . $request_id, ob_get_clean(), $cached_ajax_expiration_time ); | |
}, 0 ); | |
} | |
function get_rocket_request_uniqid_171286() { | |
return hash( 'crc32', $_SERVER['REQUEST_URI'] . serialize( $_POST ) ); | |
} | |
function rocket_is_json_171286( $string ) { | |
return is_string( $string ) && is_array( json_decode( $string, true ) ) && ( json_last_error() == JSON_ERROR_NONE ) ? true : false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment