Part 3: WordPress REST API - creating an app for publishing posts

WP REST APIWP REST API use in practice:
creating an app for publishing posts

The REST API in WordPress has a great variety of use, as we wrote earlier in the series. In the article, we will present you one option of how to use it in practice. What exactly will you learn? We'll show you how to create an app that can display, publish, and categorize unpublished posts from a WordPress-based site.

If you haven’t work with API in WordPress yet, we recommend you to read the first parts of the series Part 1: WordPress REST API - what it can do and how can it be of use to you and Part 2: A Beginners' guide to WordPress REST API. Now let's move to our app.

Imagine that we want to create an app that will be tasked with joining a requested WordPress site and displaying unpublished posts. It will allow us to view each post and eventually publish it. Additionally, the app allows us to categorize posts or assign labels to them.

1. Authentication

Because we will need to make changes and view unpublished posts on the site through our app, we will need to authenticate. The Authentication documentation topic discusses these options. For testing purposes, we can use basic authentication, which means we will send our login information to each REST API request.

2. Wordpress website verification and the basic API address

After solving the authentication, our application is ready to communicate with the site. First, we need to verify that WordPress is located on the specified address and what is the basic address of its API. This is done by sending a HEAD request to the HTTP site address.

HEAD http://www.example.com

Note: Change to domain example.com to your own.

If there is WordPress running on that address, we will receive a link array in the response headers that contains the following:

Link: <http://www.example.com/wp-json/>; rel=https://api.w.org/

It shows that the relationship (rel), https://api.w.org/' (URI pro WordPress REST API) points to http://www.example.com/wp-json/. All of our other requests that our applications will send will be based on this point.

Just to be clear, we should be able to send an HTTP GET request to the basic endpoint API and make sure that in the reply under the “namespaces” key there is also a list of namespaces, “wp/v2” where all endpoints are located with which we will control the site. The Discovery documentation topic discusses API surveys further.

3. Getting a list of posts

If we can make sure that we will understand the site we want to connect to, we can go on to get a list of posts. On the basis of the previously obtained information and verification, we can compile an endpoint for getting posts, which in this case is:

GET http://www.example.com/wp-json/wp/v2/posts

We'll get a list of the 10 most recent posts. In order to get a larger list, say 50 posts waiting to be published, we need to add the GET parameters to the endpoint according to the documentation List Post topic as follows:

GET http://www.example.com/wp-json/wp/v2/posts?status=pending&per_page=50

The answer is a collection of JSON posts, a set of feature properties enclosed in compound parentheses {}, and the entire collection enclosed in square brackets []. For example:

[
	{
		"id":31,
		"modified":"2018-11-21T11:31:05",
		"title":{
			"rendered":"My first post"
			},
		...
	},
	{
		"id":32,
		"modified":"2018-11-21T11:32:33",
		"title":{
			"rendered":"My second post"
			},
		...
	},
	...
]

 

In our application, we'll want to see the title, author name and last edit date in the list for each post. In addition, we need to remember each post's ID that we will need in other requests.

If we investigate the answer, we will find that the name of the author is given only by his ID. However, the "links" section also contains an "author" relationship pointing to an endpoint that provides information about the author of the post, and the "embeddable" attribute set to "true". This means that if we want, information about the author can be included in the answer without having to make another request to the API. The parameters of the discussed endpoint are then slightly modified:

GET http://www.example.com/wp-json/wp/v2/posts?status=pending&per_page=50&_embed

The _embed parameter causes all objects from a relationship that have an attribute "embeddable" with the value "true" to be included directly in the response, specifically for each post in "_embedded". The key names in this section correspond to the names of the links in the "_links" section.

The inbuilt objects may not have all of their properties at this point, which is given by the embed context. WordPress distinguishes between three contexts (default view, edit, or embed) in which objects such as posts, users, or categories can be presented.

One entry in a list of posts can appear in the JSON format as you can see in the example.

In order to list the posts in our application, we need the following properties from each article object:

  • "id"- post ID.
  • "title"."rendered” - Post title. We use the "rendered" subtitle of the "title" object, which has a name already formatted for display. Viewing a post title can affect the active add-ons and site template.(viz filtr the_title).
  • "modified" - Time of the last change based on ISO 8601, that we need to format into a more readable format.
  • "_embedded”.”author”[0].”name - Author's name under „name“ property of first and only object in the field of subproperty „“_embedded”.”author”.

When a user clicks on a post, their details will appear in our app. In addition to the name, date of last change, and the name of the author, we already wish to display its contents. This is not included in the answer to the collection because the entries are in the embedded context, so we need to send a request to the endpoint where we get the details of the post, including its content. The endpoint shape based on the Retrieve and Post documentation for our site will be:

GET http://www.example.com/wp-json/wp/v2/posts/<id>

where <id> is the post ID, whose details we want to retrieve. In the response under the property "content"."rendered", we find the HTML content code of the post that passed the_content filter and can be viewed immediately.

4. Displaying categories and tags

To display the categories and labels assigned to the post, it is also preferable to use the _embed parameter, for example, for a post with ID 123 we will request an endpoint:

GET http://www.example.com/wp-json/wp/v2/posts/123?_embed

The categories are listed under "categories" and labels under "tags". In these enumerations, only the terms ID are listed that must be matched with the term objects found in the collection under the property "_embedded"."wp:term"[0] and then for each term we can list its name from the "name".

5. Publishing a post

We said earlier that our app will be able to edit categories and labels and switch the post status from pending to publish. As far as publishing is concerned, we only need a POST for the same endpoint as the acquisition of detail, instead of the GET method. In the request body, we need to indicate which features of the post we want to change. Specifically, for example, to publish a post with ID 123, we make a request:

POST http://www.example.com/wp-json/wp/v2/posts/123
{“status”:”publish”}

If the change of status is in order, our app should receive a response with the post information, this time in the context of the edit type, with "status" already in the "publish" value.

6. Changing categories and tags

Regarding the change of categories and labels, we will proceed similarly, only in the body of the request we will introduce new lists of categories and labels, e.g. for our post with ID 123:

POST http://www.example.com/wp-json/wp/v2/posts/123
{
 “categories”:[2,4],
 “tags”:[3,5,6]
}

 

Which says that the post should belong to categories with ID 2 and 4 and under labels with IDs 3, 5 and 6. Old categories and labels are overwritten and replaced with new ones.

7. User-friendliness

This is the background of this operation, of course for our users, our applications must create a friendly interface, simple to enter any ID. If we do not want to be too complicated, we already have the categories and labels created on the site and we do not have the ability to create new categories and labels, although of course, we can do so by using the appropriate endpoints, just study the Create a Category or Create a Tag. In order for a user of our app to choose from a list of categories and labels, we need to get their collection of terms. For categories, endpoint http://www.example.com/wp-json/wp/v2/categories is on our site, and for http://www.example.com/wp-json/wp/v2/tags labels. Of course, we'll use the HTTP GET method to get it, and we'll receive a response of a similar format in both cases, as both categories and labels are taxonomy.

We have "id" and "name" properties of each term object for listing. Of course, when writing lists, we will label a category or label in our application that is already assigned to the post (the "categories" and "tags" attributes in response to the post details). When the user in our app marks and unmarks all categories and labels as they wish, we collect the list of marked categories and labels and make the above-discussed request (in section 6: Changing categories and labels).

 

 

The right place for your data

OUR DATA CENTERS ARE LOCATED IN PRAGUE AND BRNO