Created
March 17, 2022 09:34
-
-
Save soderlind/3f390f35346cac4bae186b38086f3022 to your computer and use it in GitHub Desktop.
WordPress REST Response as a must-use plugin, inspired by https://deliciousbrains.com/comparing-wordpress-rest-api-performance-admin-ajax-php/
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 | |
add_action( 'muplugins_loaded',function() : void { | |
$my_rest_endpoint = '/wp-json/super-admin-all-sites-menu/v1/sites/'; | |
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); | |
/** | |
* Bail if not the correct request. | |
*/ | |
if ( $my_rest_endpoint !== trailingslashit( $request_uri ) ) { | |
return; | |
} | |
/** | |
* Get HTTP Raw POST data. | |
*/ | |
$params = json_decode(file_get_contents("php://input"), true); | |
/** | |
* Bail if not an array, and not the correct request. | |
*/ | |
if ( ! is_array( $params ) && ! isset( $params['offset'] ) ) { | |
return; | |
} | |
/** | |
* Sanitize the request. | |
*/ | |
$offset = filter_var( wp_unslash( $params['offset'] ), FILTER_VALIDATE_INT, [ 'default' => 0 ] ); | |
/** | |
* Your code here. | |
* | |
* e.g.: | |
*/ | |
$offset = $offset + 100; | |
/** | |
* Set the response. | |
*/ | |
$response['response'] = 'success'; | |
$response['data'] = $offset; | |
/** | |
* Send JSON response. | |
* wp_send_json() sets the correct HTTP headers and stops the execution of the script. | |
*/ | |
wp_send_json( $response ); | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment