Create POST in WordPress with JSON API using Node.js

In this tutorial, we’ll learn how to create post in WordPress using the JSON API and OAuth2 authentication with Node.js. We will use axios for making HTTP requests. This tutorial is ideal for developers looking to integrate WordPress functionalities into their Node.js applications.

Introduction

Working with the WordPress JSON API opens a multitude of options for developers. One of the core functionalities is creating posts programmatically. In this tutorial, we will be using Node.js and axios to communicate with the WordPress API secured with OAuth2.

Prerequisites

  • A working WordPress site with JSON API plugin installed
  • OAuth2 authentication set up on the WordPress site
  • Node.js installed on your machine
  • An understanding of JavaScript and asynchronous programming

Initial Setup

First, we need to install the necessary Node.js packages.

npm install axios

Generating the OAuth Code

The first step in OAuth2 authentication is to obtain an authorization code.

async function generateOAuthCode() {
    // Replace 'YOUR_WEBSITE_URL' and 'CLIENT_ID' with your own credentials
    const authUrl = `YOUR_WEBSITE_URL/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=SCOPE`;
    try {
        const result = await axios.get(authUrl);
        // Your logic to extract the authorization code from the result goes here
        return result.data.code;
    } catch (error) {
        console.error('Error obtaining OAuth code:', error);
        return null;
    }
}

Note: You’ll need to handle the redirection and code extraction based on your OAuth setup.

Getting the Access Token

Once you have the authorization code, the next step is to exchange it for an access token.

async function getAccessToken(authorizationCode) {
    const tokenUrl = 'YOUR_WEBSITE_URL/oauth/token';
    const tokenData = {
        grant_type: 'authorization_code',
        code: authorizationCode,
        client_id: 'CLIENT_ID',
        client_secret: 'CLIENT_SECRET',
        redirect_uri: 'CALLBACK_URL'
    };
    try {
        const response = await axios.post(tokenUrl, tokenData);
        const accessToken = response.data.access_token;
        return accessToken;
    } catch (error) {
        console.error('Error obtaining access token:', error);
        return null;
    }
}

Creating the Post

When making a POST request to the /wp-json/wp/v2/posts endpoint to create a new post in WordPress via the REST API, you will include parameters in the body of the request to specify the details of the post you’re creating.

Here are some common parameters you may include in the request:

  • title (string): The title for the new post.
  • content (string): The content of the post.
  • status (string): The status of the post. Options include ‘publish’, ‘pending’, ‘draft’, ‘auto-draft’, ‘future’, ‘private’, ‘inherit’, ‘trash’. Default is ‘draft’.
  • categories (array of integers): The IDs of the categories you want to assign to the post.
  • tags (array of integers): The IDs of the tags you want to assign to the post.
  • excerpt (string): The excerpt of your post, if any.
  • author (integer): The ID of the user who will be listed as the author of the post. This user must have the appropriate capability to publish posts.
  • featured_media (integer): The ID of the featured image for the post.
  • comment_status (string): Whether or not comments are open on the post. Options are ‘open’ or ‘closed’.
  • ping_status (string): Whether or not the post can be pinged.
  • format (string): The format of the post. Options are ‘standard’, ‘aside’, ‘chat’, ‘gallery’, ‘link’, ‘image’, ‘quote’, ‘status’, ‘video’, ‘audio’.
  • meta (array): Meta fields to be added to the post.
  • slug (string): An alphanumeric identifier for the post derived from the title. It’s used in the URL of the post.

Sample Request:

{
  "title": "My First REST API Post",
  "content": "Content of the first post.",
  "status": "publish",
  "categories": [12, 14],
  "tags": [34, 56],
  "excerpt": "A brief summary of my first post.",
  "author": 1,
  "featured_media": 0,
  "comment_status": "open",
  "ping_status": "open",
  "format": "standard",
  "meta": {
    "custom_field": "value"
  },
  "slug": "my-first-rest-api-post",
  "password": "myPostPassword"
}

 

With the access token, you can now proceed to create a post.

async function createPost(accessToken, postData) {
    const createPostUrl = 'YOUR_WEBSITE_URL/wp-json/wp/v2/posts';
    try {
        const response = await axios.post(createPostUrl, postData, {
            headers: {
                'Authorization': `Bearer ${accessToken}`
            }
        });
        console.log('Post created successfully:', response.data);
        // Output: Post created successfully: <the created post object>
        return response.data;
    } catch (error) {
        console.error('Error creating post:', error);
        return null;
    }
}

To use these functions and create a post, you might call them like so:

async function main() {
    const code = await generateOAuthCode();
    if (code) {
        const token = await getAccessToken(code);
        if (token) {
            await createPost(token, {
                title: 'Hello World!',
                content: 'This is our first post created using the JSON API.',
                status: 'publish'
            });
        }
    }
}
main();

Details about Create POST API

Troubleshooting Tips

  • Ensure that your WordPress JSON API plugin is properly configured and active.
  • Check that the client ID, secret, and callback URLs match with your WordPress OAuth2 provider settings.
  • Make sure you have the correct permissions to create posts through the API.
  • Look at the error messages returned by the catch block, they usually give insight into the issue.

Conclusion

In this tutorial, we’ve learned how to create a post with WordPress JSON API using OAuth2 tokens and Node.js. Make sure to replace placeholder credentials with your actual data when implementing the code.

References