Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Last active July 30, 2021 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BhargavBhandari90/6aa4499340511cc5c33c0b1448ac44f3 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/6aa4499340511cc5c33c0b1448ac44f3 to your computer and use it in GitHub Desktop.
Change REST API Response in WordPress
<?php
/**
* Change the REST response
*
* @param object $rest_ensure_response
* @param object $instance
* @param object $request
* @return object
*/
function change_rest_api_reposne( $rest_ensure_response, $instance, $request ) {
// Get result data.
$data = $rest_ensure_response->get_data();
// Get current route.
$matched_route = $rest_ensure_response->get_matched_route();
// Check for the endpoint for which you want to change the response.
if ( strpos( $matched_route, 'your-endpoint-slug' ) === false ) {
return $rest_ensure_response;
}
// Change response based on your need.
$data = array_map(
function ( $v ) {
// Change the response based on your desired condition.
if ( isset( $v['action'] ) && 'inapp' === $v['action'] ) {
$v['namespace'] = 'url'; // Do your stuff
}
return $v;
},
$data
);
$rest_ensure_response->set_data( $data );
return $rest_ensure_response;
}
add_filter( 'rest_post_dispatch', 'change_rest_api_reposne', 10, 3 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment