首页 > 解决方案 > 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";
    }

}

标签: wordpresswordpress-rest-api

解决方案


解决方案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。


推荐阅读