Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Example of returning non-JSON results from the WP-API
<?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
You can’t perform that action at this time.