Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
WordPress: Example of returning non-JSON results from the WP-API
// reference
// 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:
// 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
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;
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.