Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BODA82/d69b91d7122eb82a466a124dcb462298 to your computer and use it in GitHub Desktop.
Save BODA82/d69b91d7122eb82a466a124dcb462298 to your computer and use it in GitHub Desktop.
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