I find quite strange that nobody ever provided support for that. Googling about JSON support for WordPress did not return anything relevant. At all.

I use the JSON support in my home page. It is used to display the last 5 blog entries of this blog in the side bar. It does not appear at first as I did not want to clutter the page, so you need to hover the mouse over the blog section and you will see it appear using a nice fading (thanks to jquery).

Anyway here is the php code for WordPress. It is not a plugin because it does not interract with the heart of the system and WordPress does not seem to have an architecture for adding that kind of feature. I believe it should rather be a core feature of the product rather than an extension.

First step, create a file called wp-json.php at the root of WordPress:

if (empty($wp)) {
require (ABSPATH . WPINC . '/feed-json.php');

Then create a file named feed-json.php in the wp-includes folder:

header('Content-Type: application/json; charset=' . get_option('blog_charset'), true);
$more = 1;

$items = array();
while (have_posts()) :
$item = array(
	"title" => get_the_title_rss(),
	"link" => apply_filters('the_permalink_rss', get_permalink()),
	"description" => apply_filters('the_excerpt_rss', get_the_excerpt()));
$items[] = $item;

$arr = array(
'title' => get_bloginfo_rss('name'),
'link' => get_bloginfo_rss('url'),
'description' => get_bloginfo_rss('description'),
'language' => get_option('rss_language'),
'item' => $items);

echo "".$HTTP_GET_VARS["callback"]."(".json_encode($arr).");";

Then the URL to use it is http://yourdomain/yourpath/wp-json.php?callback=myfunction. The callback is mandatory (if you don’t want it, modify the php script above) in order to make the feed mashable directly in a web page. It will return data like:

	"title":"It is what it is",
	"link":"http:\/\/blog.julienviet.com","description":"A pure technical trip",
	"language":"en", ...

I’ll explain later in another post how I consume it in my home page.

blog comments powered by Disqus


14 August 2008