【问题标题】:WordPress Api error: "Sorry, you are not allowed to create new posts."WordPress Api 错误:“抱歉,您不允许创建新帖子。”
【发布时间】:2016-11-07 21:14:13
【问题描述】:

我正在使用当前的 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

有人可以帮忙吗?

【问题讨论】:

  • 您是否尝试过安装 basic-auth 插件?
  • 我做了,但没有进展 - 我认为插件无法帮助我,因为这是最新的 WP (5.2.2)
  • 你认证了吗?

标签: wordpress .htaccess google-apps-script


【解决方案1】:

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

如果你使用 fetch,你可以这样做......

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

或将其作为 '_wpnonce'

添加到您的查询变量中

您可以在 第 834 行(版本 5.2.1)

上的 wp-includes/rest-api.php 找到将当前用户设置为 0 的代码

【讨论】:

  • 如何调用 api 来获取 nonce 以添加新的自定义帖子,比如“book”?
  • 它给了我错误:“code”:“rest_cookie_invalid_nonce”,“message”:“Cookie nonce 无效”,“data”:{“status”:403 }
猜你喜欢
  • 2020-12-10
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 2011-08-25
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多