GhitaB
GhitaB

Reputation: 3437

How to create a new WordPress post, using the wpapi for Node.js?

I tried using the wpapi module to create a post in WordPress. There is no error, the request ends with 200 Success, but the request body is an empty object and there is no post created.

var wp = new WPAPI({
   endpoint: 'http://your-site.com/wp-json',
   username: 'someusername',
   password: 'password'
});
wp.posts().create({
   title: 'Your Post Title',
   content: 'Your post content',
   status: 'publish'
}).then(function( response ) {
   console.log( response.id ); // This is undefined
})

Why is that and how can I fix that?

Upvotes: 4

Views: 2683

Answers (2)

farhan ayub
farhan ayub

Reputation: 60

You can fix this with the [Application password][1] plugin! It's for authenticating API requests such as REST API and XML-RPC. It will bypass the two-factor authentication and helps to authenticate users without providing their passwords directly. Instead, a unique password is generated for each application without revealing the user’s main password.

Use this code only!

var wp = new WPAPI({
   endpoint: 'http://your-site.com/wp-json',
   username: 'someusername',
   password: 'password'
});

Upvotes: 2

Ionică Bizău
Ionică Bizău

Reputation: 113365

Like I mentioned here, I fixed this by using the Application Passwords plugin.

The problem can appear if you have Duo Authentication and the WP API rest client fails to parse the JSON response (which is invalid indeed), but it fails silently (they have a try-catch there).

  1. Install the Application Passwords plugin
  2. Maybe create a new user (e.g. username: wpapi)
  3. Create an application password for that user and then use it in the Node.js code:

    var wp = new WPAPI({ 
      endpoint: 'http://your-site.com/wp-json',
      username: 'wpapi',
      password: 'XXXX XXXX XXXX XXXX'
    });
    

That will bypass the Duo Authentication.

Upvotes: 5

Related Questions