Last active
July 30, 2021 17:28
-
-
Save BhargavBhandari90/6aa4499340511cc5c33c0b1448ac44f3 to your computer and use it in GitHub Desktop.
Change REST API Response in WordPress
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 | |
/** | |
* 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