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:

If post is created successfully you’re going to get something like this in your browser console:

How to Create a Post using WordPress REST API in JavaScript

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

An error when creating a post in WordPress REST API
An error example when you provide a wrong application password.
Misha Rudrastyh

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

Follow me on X