WordPress Api错误:"抱歉,您不能创建新帖子。"

时间:2016-07-05 21:59:15

标签: wordpress .htaccess google-apps-script

我使用当前的Apps脚本功能向我的WordPress网站添加新帖子:

 var um_url = 'http://test.mywebsite.com/wp/wp-json/wp/v2/posts';
 var um_headers = { 
    "Accept" : "application/json",
    "Authorization": "Basic "+Utilities.base64Encode("user:passowrd"),
    "Content-type":"application/json"
        };

 var um_options = {  
   "method":"POST",     
   "headers": um_headers,
   "dataType" : 'json',
   "data": {
     title: "Foo title",
     content: "Foo content",
     status: "publish"
    }

    };

  var um_response = UrlFetchApp.fetch(um_url, um_options);
  var json = um_response.getContentText();
  Logger.log(json);
}

但是我收到了这个错误:

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

我读了其他类似的StackOverflow问题,他们通过更改.htacess文件解决了这个问题,遗憾的是,这并没有解决我的问题。 这是我的.htaccess文件

# BEGIN WP BASIC Auth
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</IfModule>
# END WP BASIC Auth



# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
RewriteBase /
RewriteRule ^index\.php$ - [E=X-HTTP_AUTHORIZATION:%        {HTTP:Authorization},QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wp/index.php [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</IfModule>

# END WordPress

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我只是遇到了几乎完全相同的问题,试图通过REST API添加一些东西。诀窍是,您需要将REST WP Nonce(名称为wp_rest)与请求一起发送,作为标头或请求变量的一部分...

如果您使用提取,则可以执行此操作...

fetch( route, {
    method: method, 
    headers: {
        'X-WP-Nonce': wpApiSettings.nonce
    }
} )

或将其作为'_ wpnonce'

添加到您的查询变量中

您可以在第834行(版本5.2.1)上的wp-includes/rest-api.php中找到将当前用户设置为0的代码