Create a Post with WordPress REST API using JavaScript
In the previous tutorial we discussed how you can create WooCommerce products by sending REST API requests in JS, so I kind of liked this topic and decided to take a deeper look at regular WordPress posts as well, besided there is almost no similar information out there.
The main struggle here of course is to send POST API requests in JavaScript. When you need to get posts, it is simple – just use fetch() and there we go. But when we need to authenticate – how we can do that so nobody can obtain our site application data by just inspecting the code?
The answer is Node.js of course. And there you can either go with the custom solution using axios and dotenv which is not a very complicated way comparing to the WordPress library node-wpapi but the whole process of configuring your Webpack could be a mess especially if haven’t done that before. So let’s just go with the library solution which works great.
All you need to do is to install it via terminal using npm i wpapi and now we’re ready to run our code.
Sending a POST REST API Request in Order to Create a WordPress Post on Another Site
const WPAPI = require( 'wpapi' )
const wp = new WPAPI( {
endpoint: 'YOUR SITE/wp-json',
username: '',
password: '',
} )
wp.posts().create( {
// required:
title: 'Misha Test Post',
content: 'My post content',
// optional:
status: 'publish',
date: new Date( '2023-07-15' ),
meta: {
misha_custom_field : 'yes',
},
} ).then( function( response ) {
console.log( response )
} ).catch( function( error ) {
console.log( error )
} )A couple moments to keep in mind related to this code:
- On lines
4-6don’t forget to provide your website domain, your WordPress username and application password. - A WPAPI instance object allows us to use
wp.posts()to manage posts, the full list of methods you can find on this page and WordPress REST API docs here. titleandcontentare the only required properties when you’re creating a post, but I also decided to provide status because I don’t want my post to be created as a draft because it is a default behavior.- Don’t forget that you can not just add any custom fields you want to the post via REST API, you need to register them first.
If post is created successfully you’re going to get something like this in your browser console:

On the other hand if something goes wrong, be ready for an error like this:

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me