Introduction to WordPress REST API in JavaScript

Boost Your Blogging Productivity with the Help of WordPress REST API and JavaScript — Learn How with This Tutorial.

Olivia Brown
JavaScript in Plain English

--

A WordPress Blogger
Photo by Fikret tozak on Unsplash

In the last tutorial, you witnessed the magic of the OpenAI and Unsplash APIs generating blog content. Today, we’re taking it to the next level by using the WordPress REST API for easy content upload using JavaScript. I’ve got some practical examples that will show you how to do this with ease. We’re getting closer to wrapping up our blogging automation series with JavaScript, so let’s get started!

Prerequisites

To effectively work through this beginner friendly tutorial, you should have:

  • Node.js set up on your computer.
  • A good understanding of JavaScript.
  • A WordPress site.

What you’ll learn

In this tutorial, we’ll go over:

The full tutorial code can be found on GitHub.

Introduction to WordPress REST API

The WordPress REST API lets you control your WordPress site with code. It’s a way to access and manage your site’s data and functions using API endpoints (URLs) that correspond to different data types in WordPress. You can read, write and publish posts, and other operations using standard HTTP methods like GET, POST, PUT, and DELETE.

The API supports different data formats, like JSON and XML, so you can choose the one that works best for you.

With the WordPress REST API, you can build custom apps, integrate with other platforms and services, connect with tools like CRMs and analytics, and automate boring tasks. It’s a powerful tool that gives developers control and flexibility over their WordPress site.

Check out the official WordPress REST API documentation for more information.

Alright, let’s get down to business!

Setting Up Node Project

  1. Create a new folder with a preferred name, e.g. WORDPRESS-REST-API.
  2. Open the code editor and access the terminal.
  3. Run npm init to set up the Node project.
  4. Inside the project folder, create two new files, index.js and WordPress.js, which will hold the majority of the code.
  5. Install below npm packages for the project.
npm install axios dotenv form-data
  • Axios is a handy library for Node.js that we can use to send out HTTP requests. We’ll be using it for all our API calls.
  • dotenv will be used to store API keys in a .env file and this file will be included in .gitignore to prevent accidental sharing on GitHub.
  • The form-data library is being used here because it makes it easy to send files and other data over HTTP in a format that servers expect.

I won’t go into the specifics of these Node.js libraries, as there’s already ample information available online.

There’s a popular Node.js library called node-wpapi that makes it easy for JavaScript applications to request WordPress resources. However, as of the time of this tutorial, it seems the library hasn’t been maintained since 2021.

So, I’ve decided to show you how to create those API calls from scratch. This way, you’ll have a better understanding of how the API works and can make custom requests tailored to your needs.

Obtaining Application Password

For sending authenticated WordPress API requests, both the username and application password will be needed.

To generate an application password, log in to your WordPress admin dashboard, go to Users > Profile, then in the Application Passwords section, type a name and click ‘Add New Application Password.

Screenshot of a WordPress REST API application password
WordPress Application Password

Making API Calls — Examples

The endpoint https://www.your-domain.com/wp-json/wp/v2/ is the core of the WordPress API. A GET request to this endpoint will return a JSON response with information about the available routes.

There are over 15 endpoints available depending on your application needs, but the most commonly used ones are:

// Most commonly used WordPress REST API endpoints.
// Each endpoint provides access to all the fields within a record.

.../wp/v2/posts
.../wp/v2/categories
.../wp/v2/tags
.../wp/v2/pages
.../wp/v2/media
.../wp/v2/comments

Let’s proceed with writing the code.

In the WordPress.js file, an instantiable class called WordPress is created which takes in a wpConfig parameter containing the URL, username, and password.

// WordPress.js

import axios from "axios";

export class WordPress {
constructor(wpConfig) {
// Store the URL from the wpConfig object
this.url = wpConfig.url;

// Create the headers object with the authorization and content-type headers
this.headers = {
Authorization: "Basic " + Buffer.from(`${wpConfig.username}:${wpConfig.password}`).toString('base64'),
"Content-Type": "application/json",
};
}

}

The url and headers properties are set up using this wpConfig information, with the headers having an authorization header set to the encoded string of the username and password.

WordPress.js will hold all our API request methods, while index.js will be the entry point for calling methods in the WordPress class.

// index.js

import dotenv from 'dotenv'; // Import the dotenv library to load environment variables from a .env file
dotenv.config();
import { WordPress } from './WordPress.js'; // Import the WordPress class from the WordPress.js file

// Define configuration for connecting to the WordPress API
const wpCofig = {
url: 'https://www.your-domain.com',
username: 'olivia-brown',
password: process.env.WP_KEY
};

// Create an instance of the WordPress class
const wp = new WordPress(wpCofig);

Examples 1: Send a POST request to create a new post

Imagine you want to create a new post. To do this, we will add a createPost method in the WordPress.js file. This method will send a HTTP POST request to the …/wp/v2/posts endpoint, including the authentication header and post data. The implementation can be done as follows:

// WordPress.js

// createPost method for creating a new post
async createPost(post) {
try {
const response = await axios.post(`${this.url}/wp-json/wp/v2/posts`, post, { headers: this.headers });
return response.data;
} catch (error) {
throw new Error(`Error while creating post: ${error}`);
}
}

Then, we can simply call the createPost method in our index.js and pass in the post data to it.

// index.js

// Define a new post object
const post = {
title: 'Hello World',
content: 'My Post Content.',
status: 'draft'
};

// Call the createPost method from the WordPress instance and log the result
console.log(await wp.createPost(post));

As you can see, with just a few lines of code. It’s that simple to create your first post using the WordPress REST API.

Blog Post with ‘Hello World’ via WordPress API

Examples 2: Send a POST request to upload a media file

Now we’re going to give uploading a local image file a shot using the API. We’ll start by adding a new uploadMedia method in the WordPress.js file.

// WordPress.js

// uploadMedia method for uploading an image
async uploadMedia(path, attributes) {
// create a new FormData object
const form = new FormData();

// append the image file
form.append("file", fs.createReadStream(path));

// append the title, caption, and alt text attributes
form.append("title", attributes.title);
// form.append("caption", attributes.caption);
// form.append("alt_text", attributes.alt_text);

try {
// make a POST request to the media endpoint
const response = await axios.post(`${this.url}/wp-json/wp/v2/media`, form, {
headers: {
...this.headers,
"Content-Type": `multipart/form-data; boundary=${form._boundary}`
}
});
return response.data;
} catch (error) {
throw new Error(`Error while uploading image: ${error}`);
}
}

Just like with the createPost method, we're sending a POST request to the API but to a different endpoint this time: the media endpoint. We're also specifying the Content-Type in the headers because we're sending form-data that includes information about the image, like the title, caption, and alt text.

I left out the caption and alt-text fields on purpose for this tutorial as they do not fit within its scope. But don’t worry, I’ll dive into using OpenAI to automatically generate those fields in the grand finale of the WordPress automation series.

To include the actual image in the request, we use the fs.createReadStream method. This method is part of the fs (File System) module in Node.js, and it allows us to create a stream of the image file stored at the path on our local drive.

Now we can run uploadMedia in our index.js file and give it the path to the image and the attributes.

// index.js

// setting up attributes for the image
const mediaAttributes = {
title: "Laptop with Code",
};

// specify the path to the image
const path = "/your-image-path/image.jpg";

// calling the uploadMedia method and passing in the image path and attributes
console.log(await wp.uploadMedia(path, mediaAttributes));

Blog Post Publishing with Featured Image via REST API

Let’s put everything we’ve learned to the test. To give our blog post a featured image, we’ll need to add a new field called featured_media. This field will store the image’s ID as its value. We can easily grab the image ID from the response we get after uploading the image.

Alright, let’s update our index.js file.

// index.js

async function createPostWithFeaturedImage() {
// path to the image we want to set as the featured image
const path = "/your-image-path/image.jpg";
// upload the image to the WordPress API and get the response
const mediaResponse = await wp.uploadMedia(path, {
title: "sunrise meditation"
});

// read the content of the post from a .txt file
const postContent = fs.readFileSync('/your-post-path/post.txt', 'utf8');

// create an object to represent the post, including the featured_media field
const post = {
title: "Your Post Title",
content: postContent,
status: "draft",
// set the featured_media field to the image's ID that we got from the mediaResponse
featured_media: mediaResponse.id
};

// create the post using the WordPress API
const postResponse = await wp.createPost(post);
// log a message to the console indicating that the post was created successfully
console.log(`Post created! link: ${postResponse.link}`);
}

// call the function to create the post with the featured image
createPostWithFeaturedImage();

The new createPostWithFeaturedImage function wraps all the process of:

  • First, uploads an image to the WordPress API and gets the response
  • Reads the content of the post from a .txt file
  • Creates an object representing the post and sets the featured_media field to the image’s id obtained from the media response
  • Finally, creates the post using the WordPress API

Take a look at the screenshot below! It showcases the shiny new blog post created with the help of our createPostWithFeaturedImage function.

The image and blog post were generated in the previous tutorial using OpenAI and Unsplash API, then saved onto the local drive. The coolest part? WordPress automatically formats the post, all thanks to the HTML markups in the .txt file. How awesome is that!

Blog Post with Featured Image via WordPress API

Warp up

Awesome! If you’ve been following along, you’ve done a great job. I hope you now have a good understanding of how easy it is to build your own workflow or applications by utilizing the WordPress REST API. In this tutorial, we only covered the basics, but there are so many more exciting use cases to explore.

In the final tutorial of the WordPress Automation series, we will harness the power of OpenAI, Unsplash, and the WordPress API to automatically generate multiple SEO-friendly blog posts with just a few topic keywords.

Each post will come fully formatted with headings, subheadings, a beautiful featured image, and even a caption crediting the author. All of this will be done in real-time, without the need to save or prepare any files beforehand. So, stay tuned and get ready for the ultimate WordPress automation experience!

Further Readings

Blog Automation with JavaScript Tutorial Series

Thank you for reading! If you’ve enjoyed the tutorials and stories I’ve shared and would like to support my writing, please consider signing up to become a Medium member using my referral link.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--

I write about best practices, and innovative solutions in software development, business strategy, and online marketing, with a focus on technology.