How to create a post with WP REST API v2

Posted by

I’m trying to post an article to WordPress use WP REST API. before I do this, I check lost’s information.

Official doc:

Basic auth(WordPress plugin):

First install Basic-Auth plugin.

Now we start it:

I’m using Postman as a client and can see it that correctly set “Authorization” header in the request.

Post url:
    "title": "Your Post Title",
    "content": "Your post content",
    "status": "publish"

But I get the response like this:

{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create posts as this user.","data":{"status":401}}

I have lots of Google, here I give a solution to fix it, and a way how to debug it yourself.

Apache Rewrite

You may need to know the basic use of apache rewrite if you use apache.


Add RewriteRule in .htaccess or httpd-app.conf(bitnami)

   RewriteEngine On
   RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]

This rule is mean REDIRECT_REMOTE_USER =Authorizaiton.

Add a log to basic-auth.php in Basic-Auth code:

function json_basic_auth_handler( $user ) {
	global $wp_json_basic_auth_error;

	$wp_json_basic_auth_error = null;

	// Don't authenticate twice

zip and upload to WordPress.

Post again with postman, you got response like this:

  string(30) "Basic dddddddd="
  string(20) "/wp-json/wp/v2/posts"
  string(3) "200"
  string(30) "Basic ddddddddd="

You will see some value like REMOTE_USER, REDIRECT_REMOTE_USER, next we fix the plugin:

	if ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ) );
	else if ( isset( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ) );
	else if ( isset( $_SERVER['REDIRECT_REMOTE_USER'] ) ) {
		$authorization = \sanitize_text_field( \wp_unslash( $_SERVER['REDIRECT_REMOTE_USER'] ) );

On “else if” case in the code to fixed rest_cannot_create bug. Test it with postman, the response is ok now.

Test uese “wpapi”

var WPAPI = require('wpapi');


function create() {
    return new Promise(function(resolve, reject) {
        var wp = new WPAPI({
            endpoint: '',
            // This assumes you are using basic auth, as described further below
            username: 'user',
            password: 'pass'
            // "title" and "content" are the only required properties
            title: 'Your Post Title',
            content: 'Your post content',
            // Post will be created as a draft by default if a specific "status"
            // is not specified
            status: 'publish'
        }).then(function(response) {
            // "response" will hold all properties of your newly-created post,
            // including the unique `id` the post was assigned on creation
        }).catch(function(error) {