Skip to content

Instantly share code, notes, and snippets.

@soderlind
Created March 17, 2022 09:34
Show Gist options
  • Save soderlind/3f390f35346cac4bae186b38086f3022 to your computer and use it in GitHub Desktop.
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/
<?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