[wp-hackers] JSON API 1.0 release
Otto
otto at ottodestruct.com
Tue Jun 29 19:40:43 UTC 2010
On Tue, Jun 29, 2010 at 2:26 PM, Otto <otto at ottodestruct.com> wrote:
> BTW, it wouldn't be difficult at all to implement a JSON system using
> the built in feeds mechanism. The add_feed function is pretty darned
> powerful when you get right down to it.
Here's a quick and dirty example:
<?php
/*
Plugin Name: JSON Feed Demo
*/
add_action('init','custom_add_json_feed');
function custom_add_json_feed() {
add_feed('json','custom_json_output');
}
function custom_json_output($for_comments) {
global $post;
header('Content-Type: application/json', true);
$out_posts = array();
while (have_posts()) : the_post();
$out_posts[]=$post;
endwhile;
echo json_encode($out_posts);
}
After enabling the plugin, you'll need to update the permalinks (since
I didn't add a flush on activation). After that, /feed/json/ on
anything will produce a json output of the posts in question.
I didn't implement the $for_comments variable, which gets set when
you're asking for a comments feed. You can also implement a callback
by adding your own query variable, if you like. I'll leave those as an
exercise for the reader.
-Otto
More information about the wp-hackers
mailing list