You just need to have a handler function that is called before content is sent to the browser. Without knowing exactly what you are trying to do, here is a general function that will work:
function my_plugin_json_handler(){
/*First you should check the POST/GET Request for some variable that tells
the plugin that this is a request for your json object*/
if(!isset($_REQUEST['my_triger'] || $_REQUEST['my_trigger'] !== 'some test value')) return;
//generate your json here
echo $json; //echo your json to the browser
exit; //stop executing code (prevents the template from loading)
}
add_action('init', 'my_plugin_json_handler');
Exactly where you hook should depend on exactly what you’re doing but init
is generally a safe place. You should also probably do some kind of check to protect against unauthorized calls to your function using a nonce
.
Depending on your needs you also may want to consider doing an ajax call rather than checking $_REQUEST
on an arbitrary url.