Simple page to return some json


Silly question, but I’d like to create a page to just return some json. I tried something like this: but it tries to go through the base.php file which results in a “cannot modify header information: headers already set” error message.

Am I thinking about this in the wrong way?


I now tend to use the plugin that will eventually be incorporated into core:

In the past I have created a base-json.php and filtered sage/wrap_base based on a query string, user credentials and request header.

It’s similar in principle to the CPT example on our docs.

Thanks for the reply. I actually started out trying to use WP-API but I kept getting 404 errors. Also, with WP-API I couldn’t return my own custom data (non-post/page/WP data) right?


Nope. If you need that functionality you’re probably best off building your own endpoint.

Roger and thanks. I would not be opposed to seeing an example of your filtered sage/wrap_base if you’re amenable :smile:?


I can’t post the code in production because of the credential checks. I’ve edited the CPT example from our docs to demonstrate how it can be used to respond in json to any ajax request.

add_filter('sage/wrap_base', __NAMESPACE__ . '\\sage_wrap_base_json'); // Add our function to the sage_wrap_base filter

function sage_wrap_base_json($templates) {
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' ) {
       array_unshift($templates, 'base-json.php'); // Shift the template to the front of the array
    return $templates; // Return our modified array with base-json.php at the front of the queue