[wp-hackers] Building a JSON API style plugin

Otto otto at ottodestruct.com
Wed Nov 2 17:38:12 UTC 2011


On Wed, Nov 2, 2011 at 10:51 AM, Tom Barrett <tcbarrett at gmail.com> wrote:
> I want to add some trivial JSON requests to a site. I'm wondering if there
> is a best practice for this. I have various thoughts on this, but nothing
> terribly concrete yet.
>
> 1. Is template_redirect the best hook point?
> 2. If I don't want to use the query string (e.g. /api/ticket/1234.json)
> will I get caught up in the rewrite system?

For one-offs and testing and such, I generally implement stuff like
this as a Page Template instead. Then I can create a new Page with the
URL I want, hook it to that template, and you're off and running with
very little code.

If it was something I was putting in a plugin or releasing, then
template_redirect is where I'd generally put it, with some additional
rewrite rules to make the URLs pretty. This is fairly easy to do,
actually. Say you wanted to have the URLs look like /ticket/12345:

add_action('init','ticket_add_rewrite');
function ticket_add_rewrite() {
       global $wp;
       $wp->add_query_var('ticket');
       add_rewrite_rule('ticket/([0-9]+)/?$',
'index.php?ticket=$matches[1]', 'top');
}

Then you visit the permalinks page to make it rebuild the rules, and
voila. You'll get the ticket number with get_query_var('ticket'). So
you'd change to something like this:

add_action( 'template_redirect', 'get_ticket' );
function get_ticket(){
 $ticket_num = get_query_var('ticket');
 if ( empty($ticket_num) ) return;
 $ticket = get_ticket_details($ticket_num);
 header('Content-Type: application/json');
 echo json_encode($ticket);
 exit(0);
}

(note, code written on the fly, might be buggy or not work at all, YMMV)

-Otto


More information about the wp-hackers mailing list