WP Rest API不允许通过Laravel请求发布匿名评论

问题描述 投票:0回答:1

我正在使用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...)

Api类别:

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";
    }

}

wordpress wordpress-rest-api
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.