-
-
Save macbre/5424b0c85c9278b34659d872aa2f0f41 to your computer and use it in GitHub Desktop.
WordPress: Example of returning non-JSON results from the WP-API
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 | |
// reference https://github.com/WP-API/WP-API/blob/develop/lib/infrastructure/class-wp-rest-server.php | |
// serve_request() function | |
add_filter( 'rest_pre_serve_request', 'multiformat_rest_pre_serve_request', 10, 4 ); | |
function multiformat_rest_pre_serve_request( $served, $result, $request, $server ) { | |
// assumes 'format' was passed into the intial API route | |
// example: https://baconipsum.com/wp-json/baconipsum/test-response?format=text | |
// the default JSON response will be handled automatically by WP-API | |
switch ( $request['format'] ) { | |
case 'text': | |
header( 'Content-Type: text/plain; charset=' . get_option( 'blog_charset' ) ); | |
echo $result->data->my_text_data; | |
$served = true; // tells the WP-API that we sent the response already | |
break; | |
case 'xml': // I guess if you really need to | |
header( 'Content-Type: application/xml; charset=' . get_option( 'blog_charset' ) ); | |
$xmlDoc = new DOMDocument(); | |
$response = $xmlDoc->appendChild( $xmlDoc->createElement( 'Response' ) ); | |
$response->appendChild( $xmlDoc->createElement( 'My_Text_Data', $result->data->my_text_data ) ); | |
echo $xmlDoc->saveXML(); | |
$served = true; | |
break; | |
} | |
return $served; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment