API

An Updated Overview of the WordPress JSON API in WordPress 4.4

I previously wrote about the first version of the WordPress JSON API here, but turns out, it’s not accurate anymore! Here’s an update of the code in that post; using this, you’ll be able to utilize the version two infrastructure of the API that is now in core WordPress 4.4. To use the core endpoints, you will still need to install the version two of the endpoint plugin.

JSON API OVERVIEW

Activate it and you now have a REST API for your site’s content. The plugin exposes your data in JSON format in the following content types:

  • Posts
  • Pages
  • Media
  • Custom Post Types
  • Post Meta
  • Revisions
  • Comments
  • Terms
  • Users

The response data is like what you would get in the WordPress loop, only the format is JSON. This allows you to display it in any way you wish. You can even filter the API calls in a similar fashion to the loop.

Want to get your site’s posts?
Simply send a GET request to url.com/wp-json/wp/v2/posts.

Update user with ID 4?
Send a POST request to url.com/wp-json/wp/v2/users/4.

Return all posts with the search term “awesome”?
GET url.com/wp-json/wp/v2/posts?filter[s]=awesome. It’s that easy.

Some API calls require authentication, just like WordPress requires authentication to access wp-admin or to create new posts. Most GET requests do not require authentication; this allows you to display content via the API on the front of your site or in an external app without needing the user to login.

Here is an example AJAX call to filter the posts API endpoint response:

$.ajax({
    url: 'http://url.com/wp-json/wp/v2/posts',
    data: {
        filter: {
        'posts_per_page': 5
        }
    },
    dataType: 'json',
    type: 'GET',
    success: function(data) {
        // success code
    },
    error: function() {
        // error code
    }
});

Most any filter for get_posts can also be used to filter the post’s JSON response. The other API endpoints are filtered in much the same way.

Also, you can use authenticated API calls to PUT or DELETE content. To edit a post, you send a PUT request to the API at url.com/wp-json/wp/v2/posts/id (where id is the post id you wish to edit). To add meta to a post, send a post request to url.com/wp-json/wp/v2/posts/id/meta and in your AJAX, supply a key and value in the data parameter.

In a lot of cases, people choose WordPress as their CMS because it’s easy to add new content types. Another benefit of the JSON API is it works well with Custom Post Types (CPT). To access a CPT you add a type parameter to the API request (url.com/wp-json/wp/v2/posts?type=cpt); and you can add any other get post filters as well.

There is one gotcha with posts, which is that custom meta is not added for you. If you want to include custom meta, it is easy to add with a filter to rest_prepare_post.

Example function to add meta to posts:

function custom_rest_api_prepare_post( $post_response, $post, $context ) {

    $meta = get_post_meta( $post['ID'] );
    $post_response[‘meta_field_name’] = $meta;

    return $post_response;
}
add_filter( 'rest_prepare_post', 'custom_rest_api_prepare_post', 10, 3 );

There is also some great documentation for the API. Read through them and even check out issues on Github to get a better handle on current state of the API.

API USAGE

You may be asking why you need a JSON API in WordPress. There are many reasons, but the main reason is that it allows access to data without any constraints on its usage. This allows developers to create unique experiences–one of them being custom applications. Also, plugins and themes can access the data on your site and display the content more efficiently than reloading the entire page. Sections of a site can be updated live or with user interaction.

Maybe you have a Multisite install and each subsite is a store. You may want to display all of the sales items from each site on the network that are tagged “Halloween.” The API makes these types of data mash-ups very easy to implement.

Maybe you want to post to your WordPress site from a web connected device. Smart devices have been gaining momentum for years; apps from these devices can access your API and your site will handle the request.

I could list a hundred more ideas for usage but the point of why we need and API in WordPress is that if every WordPress site is running a similar API data structure, and the sites data is open, amazing things can be created.

This post is the first in a series where I will go deeper into all aspects of the API; keep an eye out!

Some Additional Resources Worth Checking Out

http://v2.wp-api.org
https://wordpress.org/plugins/json-rest-api
http://apppresser.com/using-wordpress-rest-api-mobile-app
http://wordpress.tv/2014/07/06/rachel-baker-put-your-content-to-rest-with-wp-api
http://wordpress.tv/2014/10/13/andrew-nacin-post-modern-wordpress

Comments

12 thoughts on “An Updated Overview of the WordPress JSON API in WordPress 4.4

  1. I’m fired up for this!

    Question…what is to stop people from using your api in their own site for content? Is there ways to restrict the api to display only via special keys associated to an IP address?

    1. What’s to stop someone from scrapping your blog posts from how you currently display them? I wouldn’t worry too much about already public content.

      The API respects any privacy settings in WordPress.

  2. Thanks for the update fella!

    Question: d’ya know if its possible to “register” a user using the json api? I need to allow users to register (from within an android app) to allow them to comment on ‘registered users only’ posts.

    Thanks a bunch man

  3. I’m also hoping for a JSON formatted non-HTML content to embed content both in Mobile apps as well as websites. Is there a way I can get *only* the content without the markup?

    1. To get the data in any other format you would have to make the REST call from a script on the server and then transform the data into the format you want. You would then access your script instead of the direct REST call to WordPress.

      Alternately, you could use a Javascript function to retrieve the data from WordPress and then transform it in the function before displaying it in the browser. There’s a good example in the article of just that kind of function although the transformation is left as an exercise for the reader.

      You would have to go through this step for any sophisticated use of the data. Most programmers would prefer to get the data from WordPress with no changes and then transform it themselves.

Have a comment?

Your email address will not be published. Required fields are marked *

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress