There are many plugins that currently perform this task, so this post is for those who want to create their own JSON feed or are fans of DIY projects.
Why create a JSON feed? You might want to include a list of your blog posts on another website, which is usually done using RSS or Atom. However, creating a parser for these formats is often complicated and involves transferring a large amount of data. In contrast, JSON is a very lightweight format that we can easily manipulate with JavaScript.
Now let’s get started!
First, create a file named wp-json.php in the root directory of your blog (where wp-config.php is located). This file should contain the following:
/wp-json.php
<?php
if (empty($wp)) {
require_once(‘./wp-load.php’);
wp(‘feed=json’);
}
require(ABSPATH . WPINC . ‘/feed-json.php’);
?>
Next, we create a file named feed-json.php in the wp-includes folder of our blog. This file should contain the following:
/wp-includes/feed-json.php
<?php
header(‘Content-Type: application/json; charset=’ . get_option(‘blog_charset’), true);
$more = 1;
$items = array();
query_posts(“”);
while (have_posts()) :
the_post();
$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;
endwhile;
$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).”);”;
Finally, to test our feed, we go to http://miblog.com/wp-json.php and we’ll see our new feed in JSON format. You can find more attributes to use in WordPress.
Leave a Reply