WP Rest API 不允许通过 Laravel 请求发布匿名评论 [英] WP Rest API not allowing to post anonymous comments through a Laravel request

查看:25
本文介绍了WP Rest API 不允许通过 Laravel 请求发布匿名评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 WP REST API 来获取 Laravel 项目中的帖子.它不允许针对特定帖子发表匿名评论.我也更新了我的functions.php

I'm using WP REST API to get posts in a Laravel project. Its not allowing to post anonymous comments against a specific post. I have updated my functions.php as well

这里是错误:

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

}

推荐答案

解决方案 1:

与 GET 请求一样,您也可以使用 POST 请求来发布数据.您需要做的是通过 POST API 调用传递授权标头.
您可以在此处获取有关授权机制的更多详细信息:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

标题:

Authorization:Bearer <token>
Content-Type:application/json

您需要传递到 Params 数组中的标题.

Headers you will need to pass into the Params Array.

解决方案 2:

如果您想以匿名用户的身份发表评论,请按照以下步骤操作:
打开您的 WordPress 主题的 functions.php,并添加以下代码段:

add_filter( 'rest_allow_anonymous_comments', '__return_true' ); 

然后尝试运行您已经编码的代码段.我建议使用解决方案 1.

And than try to run the Snippet that you have coded already. I would suggest to use the Solution 1.

这篇关于WP Rest API 不允许通过 Laravel 请求发布匿名评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆