wordpress - WP Rest API 不允许通过 Laravel 请求发布匿名评论
问题描述
我正在使用 WP REST API 来获取 Laravel 项目中的帖子。它不允许针对特定帖子发布匿名评论。我也更新了我的functions.php
这是错误:
{"code":"rest_cannot_read_post","message":"Sorry, you are not allowed to read the post for this comment.","data":{"sta (truncated...)
接口类:
public static function postComments($postId, $author_name, $author_email, $content){
$url = config::get('app.WP_BASE_URL') . '/wp-json/wp/v2/comments?author_name='. $author_name.'&author_email='. $author_email.'&content='. $content.'&post='. $postId;
$params = [
'post' => $postId,
'author_email' => $author_email,
'author_name' => $author_name,
'content' => $content
];
$data = Wpapi::curlPostRequest($url, $params);
return $data;
}
控制器:
public function postComment(Request $request){
$id = $request->input('id');
$data = $request->validate([
'name' => 'required|max:255',
'email' => 'required',
'comment' => 'required',
]);
$author_email = $data['email'];
$author_name = $data['name'];
$content = $data['comment'];
$postComment = Wpapi::postComments($id, $author_name, $author_email, $content );
if($postComment){
echo "Success";
}
else {
echo "Failure";
}
}
解决方案
解决方案1:
与GET请求一样,您也可以使用POST请求来发布数据。您需要做的是通过 POST API 调用传递授权标头。
您可以在此处获取有关授权机制的更多详细信息:https ://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
标题:
Authorization:Bearer <token>
Content-Type:application/json
您需要将标头传递到 Params 数组中。
解决方案 2:
如果您想以匿名用户身份发表评论,请按照以下步骤操作:
打开 WordPress 主题的functions.php,并添加以下代码段:
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
而不是尝试运行您已经编码的代码段。我建议使用解决方案 1。
推荐阅读
- android - android的GooglePlus登录实现离子错误
- r - 使用 NA 绘制 3D 表面忽略某些点
- c# - Worker Service 动态改变执行间隔
- reactjs - 更改材质ui中选择字段的边框颜色
- visual-studio - 打开包管理器控制台时 Visual Studio 2019 中的错误
- javascript - 有没有办法在 Nest JS 中初始化 `GraphQLExecutionContext` 以进行测试?
- python - 在 inlineformset_factory 中,无法更改主要模型的小部件(django 3.0)
- nginx - 如何使用 Nginx 代理传递将请求重定向到具有相同 slug 的两个不同上游
- rabbitmq - 将多个rabbitMQ相互连接
- coverity - 401:抱歉,您的凭据对此资源无效