Using The WordPress API

Wordpress has an app. That means there’s an API to normalize communication using a predictable programmatic interface. In this case, as with many others, that’s done using a standard REST interface to communicate. The easiest way to interact with any API is to just read some stuff from the server via curl. You can feed curl the URL to the API by using your URL followed by /wp-json – as follows, assuming a URL of http://www.krypted.com:
curl http://www.krypted.com/wp-json
To view header information:
curl -s -D - http://www.krypted.com -o /dev/null
In the below example we’ll ask for a list of posts by adding /wp/v2/posts to the URL:
curl http://www.krypted.com/wp-json/wp/v2/posts
You’ll see a list of some posts in the output along with a little metadata about the posts. You can then grab an ID and ask for just that post, using a post ID of 48390:
curl http://www.krypted.com/wp-json/wp/v2/posts/48390
You can also see revisions that have been made to a post by appending the URL with /revisions
curl http://www.krypted.com/wp-json/wp/v2/posts/48390/revisions
You can see comments with the comments route:
curl http://www.krypted.com/wp-json/wp/v2/comments
Or pages with the pages route:
curl http://www.krypted.com/wp-json/wp/v2/pages
Or users with the users route:
curl http://www.krypted.com/wp-json/wp/v2/users
Or media that has been uploaded with the media route:
curl http://www.krypted.com/wp-json/wp/v2/media
And the output of each can be constrained to a single item in that route by providing the ID of the item, which shows additional metadata about the specified item. And there are routes for categories, tags, etc.
There’s also some good stuff at https://github.com/WP-API such as https://github.com/WP-API/Basic-Auth which is a plugin that allows you to auth against the API.
curl --user admin:krypted http://www.krypted.com/wp-json/users/me
Not only can you look at user information, you can also add and remove posts. You would add by doing a -X followed by a POST and then feeding a file with the –data option
curl --user admin:password -X POST http://www.krypted.com/wp-json/posts --data @post.json
The output would then include the ID of your new post to wordpress. In the following example, we’ll get rid of the post we were looking at earlier using -X and DELETE in the URL, assuming a username of admin, a password of krypted, and a post ID of 48390:
curl --user admin:krypted -X DELETE http://www.krypted.com/wp-json/posts/48390
If successfully deleted the response would be as follows: